我在3个活动中binding
到service
,在2中效果很好,但在第3个中我遇到了错误。
这是我的服务:
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();
}
}
这是我的活动,我有一个错误:
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:尝试调用虚方法 “无效 com.gmail.krakow.michalt.myecg.ClientBluetoothService.generateToast()” 在空对象引用上
答案 0 :(得分:3)
我不知道为什么它与其他2个活动一起工作,但是在这种情况下你很自然会得到NullPointerException。 Activity生命周期中的顺序是:
onCreate() - > onStart() - > onResume() - > onPause() - > onStop() - >和onDestroy()。 (https://developer.android.com/guide/components/activities/activity-lifecycle.html)
clientBluetoothService在绑定到服务后初始化,这在onStart中完成,但是它在onCreate中使用,而onCreate总是在onStart之前运行,它给出NullPointerException。
如果你想确保在使用clientBluetoothService时初始化它,那么mBound非常有用。