在Android 5.0以后,google添加了service启动的component和package判断

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));

}

}

假如component和package为空,就会直接抛出一个IllegalArgumentException的异常,所以这就是为什么我们在5.0以前可以进行隐式启动,而到了5.0以后,隐式启动不起作用。我们可以人为的把这两个参数添加进去,代码如下:

private fun getExplicitIntent(context: Context, implicitIntent: Intent): Intent? {

val pm = context.packageManager

val resolveInfos = pm.queryIntentServices(implicitIntent, 0)

if (resolveInfos == null || resolveInfos.size != 1) {

return null

}

var explicitIntent: Intent?

val info = resolveInfos[0]

val packageName = info.serviceInfo.packageName

val className = info.serviceInfo.name

val component = ComponentName(packageName, className)

explicitIntent = Intent(implicitIntent)

explicitIntent.component = component

return explicitIntent

}

}

a353204d083c

image.png

//在新建的intent中填入的是你在清单文件中注册的action

val intent = Intent("com.m163.progress")

//调用上面的getExplicitIntent方法

_mActivity.bindService(getExplicitIntent(context!!, intent), object : ServiceConnection {

override fun onServiceDisconnected(name: ComponentName?) {

}

override fun onServiceConnected(name: ComponentName?, service: IBinder?) {

val progressBinder = service as ProgressService.ProgressBinder

progressBinder.startProgress(progressView1)

}

}, Activity.BIND_AUTO_CREATE)

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐