三、app調用服務介面訪問硬體
上主要代碼EEPROMActivity.java
package com.zkgd.eeprom;import android.app.Activity;import android.os.Bundle;import android.os.ServiceManager;import android.os.IIICService;import android.os.RemoteException;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class EEPROMActivity extends Activity implements OnClickListener{private final static String LOG_TAG = "com.zkgd.eeprom"; private IIICService iicService = null; private EditText valueText = null; private Button readButton = null; private Button writeButton = null; private Button clearButton = null; int len = 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); iicService = IIICService.Stub.asInterface( ServiceManager.getService("iic")); valueText = (EditText)findViewById(R.id.edit_value); readButton = (Button)findViewById(R.id.button_read); writeButton = (Button)findViewById(R.id.button_write); clearButton = (Button)findViewById(R.id.button_clear); readButton.setOnClickListener(this); writeButton.setOnClickListener(this); clearButton.setOnClickListener(this); Log.i(LOG_TAG, "Activity Created"); } public void onClick(View v) { if(v.equals(readButton)) { try { len = 1; //在從裝置中讀取資料 String val = iicService.getVal(0x50,len); valueText.setText(val); } catch (RemoteException e) { Log.e(LOG_TAG, "Remote Exception while reading value from device."); } } else if(v.equals(writeButton)) { try { String val = valueText.getText().toString(); len = val.length(); //在從裝置的子地址處開始寫入資料 iicService.setVal(val,0x50,0x10,len); } catch (RemoteException e) { Log.e(LOG_TAG, "Remote Exception while writing value to device."); } } else if(v.equals(clearButton)) { String text = ""; valueText.setText(text); } } }
工程eeprom放置在源碼目錄package/app/下
編譯命令:mmm package/app/eeprom
打包,燒寫韌體至開發板,啟動就可以看到該應用的表徵圖了。
小結:
整個調用流程為:app<---AIDL訪問服務<---JNI本地方法實現<---HALso檔案<---硬體
一個問題,這種方法改動了android原生api,畢竟是訪問了硬體。如果想做通用app又想使用c/c++提高效率,直接進行NDK開發,功能編譯成庫檔案打進app應用的工程中。
另一個問題,硬體訪問會遭遇到許可權問題。如果做通用app,需要裝置root了,然後在代碼裡添加許可權修改操作,例如:"chmod 777 "+getPackageCodePath(); "chmod 777 /dev/i2c-1";