【发布时间】:2017-12-28 14:14:11
【问题描述】:
我参考了有关此问题的所有其他 StackOverflow 帖子,但我无法使其正常工作。
我的目标是编写一个没有主要活动的应用程序,只是一个服务。您应该能够从单独的应用程序绑定到它并使用 AIDL 与之交互。
我之前在同一个应用程序中同时调用了服务和活动,并且它运行完美。但我需要让它在两个单独的应用程序之间工作。
服务的 onBind() 如下所示:
@Nullable
@Override
public IBinder onBind(Intent intent) {
// This binds the bluetooth service itself to the logger service, do this when the logger service itself is bound
Intent serviceIntent = new Intent(this, BluetoothService.class);
intent.setPackage(this.getPackageName());
Log.d(getClass().getName(), "started");
if(bluetoothService == null) {
if (this.bindService(serviceIntent, bluetoothServiceConnection, BIND_AUTO_CREATE)) {
Log.d(getClass().getName(), "returned the service");
return mBinder;
} else {
Log.d(getClass().getName(), "returned null");
return null;
}
} else {
Log.d(getClass().getName(), "returned the service");
return mBinder;
}
}
服务本身绑定到另一个服务,但所有的蓝牙东西都已经工作了。
包含该服务的应用程序清单如下所示:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:label="@string/app_name">
<service
android:label="LoggerService"
android:name="io.modum.ble.LoggerService"
android:exported="true">
<intent-filter>
<action android:name="io.modum.ble.LoggerService" />
</intent-filter>
</service>
<service android:name="io.modum.ble.service.BluetoothService" />
</application>
在我的活动中,我像这样绑定到它:
Intent intent = new Intent();
ComponentName componentName = new ComponentName("io.modum.modum_ble_service", "io.modum.ble.LoggerService");
intent.setComponent(componentName);
boolean success = getApplicationContext().bindService(intent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(getClass().getName(), "Service connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}, BIND_AUTO_CREATE);
Log.d(getClass().getName(), String.valueOf(success));
AIDL 文件在两个应用程序中具有完全相同的包名称。
没有异常被调用,一切正常,除了 onServiceConnected 没有被调用。
bindService() 返回 true,服务接收到意图并正确启动,记录“返回服务”,但永远不会调用 onServiceConnected()。
【问题讨论】:
-
Android 应用程序必须与用户进行某种 UI 交互才能运行后台服务,这可能是您的问题的一部分吗?见stackoverflow.com/questions/8531926/…。
-
@ScottKronheim 我让它运行起来了。显然,除了组件之外,您还必须将意图中的包设置为服务应用程序的包。安装服务应用程序后,我不需要立即运行该服务。我需要该服务在其他应用绑定后立即运行。