Android 5.0以上使用隐式启动的方法

2019-01-25  本文已影响0人  秃渐强

在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
    }
  }
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)
上一篇 下一篇

猜你喜欢

热点阅读