有谁知道为什么?
活动
private IExternalDeviceScannerService myService = null;
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
myService = IExternalDeviceScannerService.Stub.asInterface(arg1);
}
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
......
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, ExternalDeviceScannerService.class);
bindService(intent, serviceConnection,
Context.BIND_AUTO_CREATE);
....
服务
class ScannerServiceAIDL extends IExternalDeviceScannerService.Stub {
.......
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new ScannerServiceAIDL();
}
我的活动从未连接到服务,即使我等了几秒钟!
答案 0 :(得分:1)
我测试了您的代码并执行代码没有任何问题。我认为你在项目的任何地方都犯了任何错误。我成功执行的代码如下。
package com.example.aidltest;
interface IExternalDeviceScannerService
{
int getIntValue();
}
<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玩得开心!!!感谢