[英]Bindservice error
我在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:尝试在空对象引用上调用虚方法'void com.gmail.krakow.michalt.myecg.ClientBluetoothService.generateToast()'
我不知道它为什么与其他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非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.