我有一个Java后台serviceA和serviceB。我已经在Mainactivity类的onStart方法中实例化了serviceA。如果serviceA无法启动,我需要启动serviceB。我已经写了一个在MainActivity中被调用的回调方法,但是当我尝试调用serviceB时却没有被创建。
我已经在MainActivity中编写了一个回调方法,该方法在serviceA中被调用,但是当我尝试调用serviceB时却没有被创建。
public class MainActivity extends Activity implements ServiceCallbacks{
private static final String TAG = "Main Activity";
private Context myContext = null;
Intent myTestService;
private MyTestService serviceA;
private boolean bound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myContext = this;
setContentView(R.layout.activity_main);
Log.d(TAG,"onCreate called.");
}
@Override
protected void onResume() {
super.onResume();
if(serviceA == null) {
serviceA = new Intent(this, MyTestService.class);
Log.d(TAG,"onResume called.");
Log.d(TAG,"myTestService instance created.");
}
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG,"onPause called.");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"OnDestory called");
}
@Override
protected void onStart() {
super.onStart();
// bind to Service
Intent intent = new Intent(this, MyTestService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from service
if (bound) {
myService.setCallbacks(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}
/** Callbacks for service binding, passed to bindService() */
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// cast the IBinder and get MyService instance
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
bound = true;
myService.setCallbacks(MainActivity.this); // register
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
@Override
public void callBackToActivity() {
unbindService(serviceConnection);
StartNewService();
}
private void StartNewService(){
Intent intent = new Intent(this, serviceB.class);
startService(intent);
}
}
如果serviceA无法启动,我想启动serviceB。 我是c#开发人员,并且是Java的新手,需要您的帮助。