0
我想綁定多個活動服務,所以我寫了一個應用程序類來管理這個目標:與多個活動綁定服務
public class BluetoothController extends Application {
private static BluetoothController mInstance;
private ClientBluetoothService mService;
protected boolean mBound = false;
public static synchronized BluetoothController getInstance() {
return mInstance;
}
@Override
public void onCreate() {
super.onCreate();
}
public void startService(){
//start your service
Intent intent = new Intent(this, ClientBluetoothService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stopService(){
//stop service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
public ClientBluetoothService getService(){
return mService;
}
public boolean isBound() {
return mBound;
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
ClientBluetoothService.LocalBinder binder = (ClientBluetoothService.LocalBinder) service;
mService = binder.getSerivce();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
並訪問這個類在我使用例如活動:
BluetoothController.getInstance().startService();
但是我有一個錯誤:顯示java.lang.NullPointerException:嘗試調用虛擬方法「無效com.gmail.krakow.michalt.myecg.BluetoothController.startService()」上的空對象引用。 如何解決?
另外 - 根本沒有必要這樣做。如果你想將多個活動綁定到一個服務,只需在每個中調用bindService。或者把它放到你的活動的通用基類中。將它應用到應用程序中是沒有意義的 –
您打算如何使用'BluetoothController',調用'isBound()'後跟'getService()',然後用意圖手動綁定? – samosaris
這不是最好的主意。如果遵循@GabeSechan給出的指示,它運作良好。 – michalt38