首页 > 解决方案 > 如何从服务回调中调用服务

问题描述

我有一个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 新手,需要您的帮助。

标签: javaandroid

解决方案


推荐阅读