
| 12345678 | package com.sergeycao.aidlexample; // Declare the communication interface which holds all of our exposed functions.interface IAddService { // WE can pass values along with in, out, or inout parameters. // Android Java PRimitive datatypes (such as int,, string, boolean, etc.) can only be passed in. int add(in int ValueFirst, in int valueSecond);} |
| 12345678910111213141516171819202122232425262728293031323334353637383940414243 | packagecom.sergeycao.aidlexample; importcom.sergeycao.aidlexample.IAddService; importandroid.app.Service;importandroid.content.Intent;importandroid.os.IBinder;importandroid.os.RemoteException;importandroid.util.Log; /*** This AddService class exposes the remote service (functions in AIDL file, which we need to expose to other apps) to the client*/publicclassAddServiceextendsService{ privatestaticfinalStringTAG="AddService"; @Override publicvoidonCreate(){ super.onCreate(); Log.i(TAG,"onCreate()"); } @Override publicIBinderonBind(Intentintent){ returnnewIAddService.Stub(){ /** * In the AIDL file we just add the declaration of the function * here is the real implementation of the add() function below */ publicintadd(intValueFirst,intvalueSecond)throwsRemoteException{ Log.i(TAG,String.format("AddService.add(%d, %d)",ValueFirst,valueSecond)); return(ValueFirst+valueSecond); } }; } @Override publicvoidonDestroy(){ super.onDestroy(); Log.d(TAG,"onDestroy()"); }} |
将我们的远程服务暴露给本地客户端
在我们在我们的服务类中正确实现onBind()之后,现在我们准备从本地客户端连接到我们的服务。为此,我们将有一个简单的Activity类,从中我们将连接到我们的远程服务,并从服务调用暴露的add()函数。要建立服务和本地客户端之间的连接,我们需要通过在我们的活动类(在我们的例子中是AIDLActivity)的一侧实现Android ServiceConnection类来创建一个新的内部类。所以我们的AIDLActivity类通过实现onServiceConnected()和onServiceDiconnected()方法实现了AddServiceConnection内部类。这些方法是回调,它将在连接时获得远程服务的存根实现。然后我们只需要将它们从Stubs转换到我们的AIDL服务实现。所以要这样做,我们需要使用IAddService.Stub.asInterface((IBinder)boundService)辅助方法。从这里,我们将有一个本地服务指针来访问数据和方法。所以initService()是我们的方法,它从Activity的onCreate()方法中调用来建立连接。然后当我们点击“Result”按钮时,onClickButtonResult()方法将被调用,我们已经调用了我们的远程服务的add()方法。将以下文件放在源文件夹中,如下所示:/ src / com / sergeycao/ aidlexample / AIDLActivity.Java本地客户端活动文件:AIDLActivity.Java| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 | package com.sergeycao.aidlexample; import com.sergeycao.aidlexample.IAddService;import com.sergeycao.aidlexample.R; import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.util.Log;import android.view.Menu;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; public class AIDLActivity extends Activity { private static final String TAG = "AIDLExample"; IAddService service; AddServiceConnection connection; /** * This is the class which represents the actual service-connection. * It type casts the bound-stub implementation of the service class to our AIDL interface. */ class AddServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { service = IAddService.Stub.asInterface((IBinder) boundService); Log.i(TAG, "onServiceConnected(): Connected"); Toast.makeText(AIDLActivity.this, "AIDLExample Service connected", Toast.LENGTH_LONG).show(); } public void onServiceDisconnected(ComponentName name) { service = null; Log.i(TAG, "onServiceDisconnected(): Disconnected"); Toast.makeText(AIDLActivity.this, "AIDLExample Service Connected", Toast.LENGTH_LONG).show(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_aidl); initService(); } public void onClickButtonResult(View v) { TextView value1 = (TextView) findViewById(R.id.editTextValue1); EditText value2 = (EditText) findViewById(R.id.editTextValue2); EditText result = (EditText) findViewById(R.id.editTextResult); int n1 =0, n2 =0, res = -1; n1 = Integer.parseInt(value1.getText().toString()); n2 = Integer.parseInt(value2.getText().toString()); try { res = service.add(n1, n2); } catch (RemoteException e) { Log.i(TAG, "Data fetch failed with: " + e); e.printStackTrace(); } result.setText(new Integer(res).toString()); } /** This is our function which binds our activity(MainActivity) to our service(AddService). */ private void initService() { Log.i(TAG, "initService()" ); connection = new AddServiceConnection(); Intent i = new Intent(); i.setClassName("com.techblogon.aidlexample", com.techblogon.aidlexample.AddService.class.getName()); boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE); Log.i(TAG, "initService() bound value: " + ret); } /** This is our function to un-binds this activity from our service. */ private void releaseService() { unbindService(connection); connection = null; Log.d(TAG, "releaseService(): unbound."); } @Override protected void onDestroy() { super.onDestroy(); releaseService(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }} |
xml Layout (activity_aidl.xml)
我们的UI包含简单的元素。 我们使用2 EditText获取用户输入和一个按钮获得结果。 结果字段也是具有可编辑false的EditText。 您可以使用任何其他控件。 此外,我们使用Textview显示一些信息广告提示。
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 | <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/textViewTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="Enter 2 digits for addition, then click result button for getting the result form the service using AIDL."/> <EditText android:id="@+id/editTextValue1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textViewTitle" android:layout_centerHorizontal="true" android:layout_marginTop="35dp" android:hint="Enter a number" android:ems="10" android:inputType="number"/> <EditText android:id="@+id/editTextValue2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editTextValue1" android:layout_centerHorizontal="true" android:layout_marginTop="33dp" android:hint="Enter a number" android:ems="10" android:inputType="number"/> <EditText android:id="@+id/editTextResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editTextValue2" android:layout_centerHorizontal="true" android:layout_marginTop="18dp" android:editable="false" android:ems="10"/> <Button android:id="@+id/buttonResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editTextResult" android:layout_centerHorizontal="true" android:layout_marginTop="26dp" android:onClick="onClickButtonResult" android:text="Result"/> </RelativeLayout> |
Manifest文件
在最后一步中,我们将我们的服务类条目(在我们的案例中的AddService)放在我们项目的Manifest文件中,如下所示。
| 1 | <service android:name="com.techblogon.aidlexample.AddService" /> |
| 12345678910111213141516171819202122232425262728 | <?xmlversion="1.0"encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.sergeycao.aidlexample" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/APPTheme"> <activity android:name="com.techblogon.aidlexample.AIDLActivity" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <serviceandroid:name="com.techblogon.aidlexample.AddService"/> </application> </manifest> |
而已。 构建并运行应用程序。 输入2位数字,然后单击结果按钮,您可以从AIDL服务获得结果。
新闻热点
疑难解答