我在 3 个 Activity 中绑定(bind)
到一个服务
,在 2 个 Activity 中它运行良好,但在第 3 个 Activity 中我遇到了错误。
这是我的服务:
public class ClientBluetoothService extends Service {
private Handler handler = new Handler();
private final IBinder mBinder = new LocalBinder();
private ClientBluetooth clientBT;
public class LocalBinder extends Binder {
ClientBluetoothService getSerivce() {
return ClientBluetoothService.this;
}
}
public ClientBluetoothService() {
clientBT = new ClientBluetooth();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void generateToast() {
Log.d("HERE", "Service: generateToast()");
Toast.makeText(getApplicationContext(), "WITAJ W SERWISIE", Toast.LENGTH_SHORT).show();
}
public void newClient() {
clientBT = new ClientBluetooth();
}
public void start() {
clientBT.start();
}
public String getStatus() {
return clientBT.getStatus();
}
public void disconnect() throws IOException {
clientBT.disconnect();
}
}
这是我的 Activity ,其中我有一个错误:
public class MeasureActivity extends AppCompatActivity {
protected boolean mBound = false;
private ClientBluetoothService clientBluetoothService;
private TextView textView;
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, ClientBluetoothService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Log.d("HERE", "Measure: onStart()");
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_measure);
setTitle("Measure");
textView = (TextView)findViewById(R.id.textView);
clientBluetoothService.generateToast();
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
ClientBluetoothService.LocalBinder binder = (ClientBluetoothService.LocalBinder) service;
clientBluetoothService = binder.getSerivce();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
我有一个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gmail.krakow.michalt.myecg.ClientBluetoothService.generateToast()' on a null object reference
最佳答案
我不知道为什么它与其他 2 个 Activity 一起使用,但是在这种情况下,您很自然地会收到 NullPointerException。 Activity 生命周期中的顺序是:
onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> 和 onDestroy()。 ( https://developer.android.com/guide/components/activities/activity-lifecycle.html )
clientBluetoothService 在绑定(bind)到服务后初始化,这是在 onStart 中完成的,但是它在 onCreate 中使用并且 onCreate 总是在 onStart 之前运行,这会产生 NullPointerException。
如果您想确保 clientBluetoothService 在您使用时已初始化,mBound 会很有用。
关于java - 绑定(bind)服务错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46612904/