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
中的方法,都会报错,报错信息为myService
为null
,如果我在某个click
事件中执行 myService.pay();
就可以正常的执行,这是为什么
解决方案
onServiceConnected回调时候myService才会被初始化,而oncreate执行的时候myService还没有初始化
某个click事件中执行,有可能当时已经初始化了。这个问题其实是多线程问题
这篇关于Android 执行其他服务中AIDL的方法,不能再Activity的生命周期方法中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文