在android中service启动异常

xiaoxiao2021-02-28  160

记录一下开发中遇到的问题:

用intent开启一个service时

Intent intent = new Intent("com.ryg.MessengerService.launch"); bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

出现如下错误:

Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.ryg.MessengerService.launch } at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1847) at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1946) at android.app.ContextImpl.bindService(ContextImpl.java:1924) at android.content.ContextWrapper.bindService(ContextWrapper.java:539) at com.ryg.chapter_2.messenger.MessengerActivity.onCreate(MessengerActivity.java:64) 此时解决办法是:

Intent mIntent = new Intent(); mIntent.setAction("com.ryg.MessengerService.launch");//你定义的service的name mIntent.setPackage(getPackageName());//这里你需要设置你应用的包名 bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);

原因:android5.0之后service的开启必须是显示的开启

分析源码:

private void validateServiceIntent(Intent service) { if (service.getComponent() == null && service.getPackage() == null) { if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) { IllegalArgumentException ex = new IllegalArgumentException( "Service Intent must be explicit: " + service); throw ex; } else { Log.w(TAG, "Implicit intents with startService are not safe: " + service + " " + Debug.getCallers(2, 3)); } } }

转载请注明原文地址: https://www.6miu.com/read-64781.html

最新回复(0)