我测试了您的代码并毫无问题地执行了代码。我认为您在项目的任何地方都犯了任何错误。我成功执行的代码如下。
IExternalDeviceScannerService.aidl
package com.example.aidltest;
interface IExternalDeviceScannerService
{
int getIntValue();
}
清单.xml
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ExternalDeviceScannerService"></service>
</application>
活动
private IExternalDeviceScannerService myService = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ExternalDeviceScannerService.class);
// Bind service here
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
myService = null;
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
myService = IExternalDeviceScannerService.Stub.asInterface(service);
if (myService != null){
try {
Log.i("Value from AIDL", myService.getIntValue() + "");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onServiceDisconnected(ComponentName className) {
myService = null;
}
};
服务
public class ExternalDeviceScannerService extends Service {
private static final String LOG_TAG = "Service";
@Override
public void onCreate() {
super.onCreate();
Log.i(LOG_TAG, "Service Started.");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "Service Stopped.");
}
final class ScannerServiceAIDL extends IExternalDeviceScannerService.Stub {
public int getIntValue() throws RemoteException {
return 20;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i(LOG_TAG, "Service Bound.");
return new ScannerServiceAIDL();
}
}
与 AIDL 玩得开心!!!谢谢