我有一个启动服务的 Android 项目。然后我把它变成了一个 Android 库并将其添加到另一个 Android 项目中。现在我正在尝试从我的主要 Android 项目自动启动该服务,但我迷路了。这是我清单中的代码(我已经从库中添加了所有类):
<service
android:name="com.test.mqttclientserver.MQTTService"
android:enabled="true"
android:exported="false"
android:label="Service" >
<intent-filter>
<action android:name="com.test.mqttclientserver.MQTTService" />
</intent-filter>
</service>
<activity
android:name="com.test.mqttclientserver.MQTTClient"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.test.mqttclientserver.MQTTNotifier"
android:label="@string/app_name" >
</activity>
在主项目的一个活动中:
private boolean mBounded;
private MQTTService mService;
private MQTTConnectionStatus connectionStatus = MQTTConnectionStatus.INITIAL; ..... public IBinder onBind(Intent intent) {
return mBinder;
}
public MQTTConnectionStatus getConnectionStatus() {
return connectionStatus;
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(SplashScreen.this, "Service is disconnected", 1000)
.show();
mBounded = false;
mService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(SplashScreen.this, "Service is connected", 1000).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder) service;
mService = (MQTTService) mLocalBinder.getService();
}
};
public void onStart(final Intent intent, final int startId) {
System.out.println("onStart loading...");
Intent mIntent = new Intent(this, MQTTService.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
System.out.println("onStart ending...");
}
protected void onStop() {
super.onStop();
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
}
这还不够吗?一个提示就足够了。感谢您的时间。