Android5.0以后隐式启动ServiceBug

时间:2022-04-24
本文章向大家介绍Android5.0以后隐式启动ServiceBug,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

以前写过一篇关于进程间通信的博客

通信之进程间通信-AIDL

当时用的还是4.2的系统,跨进程 的服务可以根据action进行启动

                Intent intent = new Intent();

                intent.setAction("android.intent.action.aidl.server");

但是现在用6.0时发现报错

01-06 01:54:14.140: : Process: com.fang.zrf.clientdemo, PID: 18507
01-06 01:54:14.140: : java.lang.IllegalArgumentException: Service Intent must be explicit: 
                                            Intent { act=android.intent.action.aidl.server }
01-06 01:54:14.140: : 	at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1209)
01-06 01:54:14.140: : 	at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1308)
01-06 01:54:14.140: : 	at android.app.ContextImpl.bindService(ContextImpl.java:1286)
01-06 01:54:14.140: : 	at android.content.ContextWrapper.bindService(ContextWrapper.java:604)
01-06 01:54:14.140: : 	at com.fang.zrf.clientdemo.MainActivity.onClick(MainActivity.java:70)
01-06 01:54:14.140: : 	at android.view.View.performClick(View.java:5205) 

报错之处service的intent必须是明确的,显示的指出。这时候如果是在同一个应用中可以调用类名启动,那如果是不在同一个应用中之能通过service的路劲来调用了。

可以通过setComponent来调用

intent.setComponent(new ComponentName("com.fang.zrf.serverdemo",  "com.fang.zrf.serverdemo.CustomService"));

也可以通过

intent.setClassName("com.fang.zrf.serverdemo",  "com.fang.zrf.serverdemo.CustomService");

来调用,因为本质上是一样的setClassName源码也是创建了ComponentName对象

public Intent setClassName(String packageName, String className) {
        mComponent = new ComponentName(packageName, className);
        return this;
    }

其实思路就是通过packagename 和classname来调用,方法有好多。