首页 > Android 执行其他服务中AIDL的方法,不能再Activity的生命周期方法中执行?

Android 执行其他服务中AIDL的方法,不能再Activity的生命周期方法中执行?

public class MainActivity extends AppCompatActivity {

    MyConn conn;
    public Imyaidl myService;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setAction("com.example.bindservice");
        intent.setPackage("com.example.bindservice");
        conn = new MyConn();
        bindService(intent, conn, BIND_AUTO_CREATE);

        //这里报错 在 onStart ,onResume也会报错
        // 报错信息都为 myService为null
//        try {
//            myService.pay();
//            System.out.println("service1.pay();");
//        } catch (RemoteException e) {
//            System.out.println("e.printStackTrace();");
//            e.printStackTrace();
//        }

    }


    public void click(View v){
        try {
            myService.pay();
        } catch (RemoteException e) {
            System.out.println("e.printStackTrace();");
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();

    }

    class MyConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService =  Imyaidl.Stub.asInterface(service);
            //在此处可以正常执行
            try {
                myService.pay();
                System.out.println("service1.pay();");
            } catch (RemoteException e) {
                System.out.println("e.printStackTrace();");
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}

最近在学习 AIDL 我发现只要我在Activity的生命周期方法中执行myService中的方法,都会报错,报错信息为myServicenull,如果我在某个click事件中执行 myService.pay(); 就可以正常的执行,这是为什么


onServiceConnected回调时候myService才会被初始化,而oncreate执行的时候myService还没有初始化
某个click事件中执行,有可能当时已经初始化了。这个问题其实是多线程问题

【热门文章】
【热门文章】