美文网首页
Android 隐式Intent

Android 隐式Intent

作者: wkjack | 来源:发表于2019-03-06 14:11 被阅读0次

    1.判断是否匹配Intent

    // 获取包管理器
    PackageManager pm = getPackageManager();
    // 先判断系统中有没有潜在的App的Activity支持对该sendIntent的接收与处理
    if (pm.resolveActivity(sendIntent, 0) != null) {
        startActivity(sendIntent);
    }
    

    2.强制用户使用App Chooser

    用户不想每次都用同一个默认App处理这样的情形怎么办呢?这时候我们可以在代码中明确地使用App选择对话框:

    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    ...
    
    String title = "请选择想通过哪个App分享数据";
    
    // 验证是否有App能够接收并处理sendIntent
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        // 根据sendIntent创建一个需要显示App选择对话框的intent对象
        Intent chooserIntent = Intent.createChooser(sendIntent, title);
        // 我们使用chooserIntent作为startActivity()方法的参数,而非sendIntent
        startActivity(chooserIntent);
    }
    

    3.隐式调用Service

    在Android 5.0及以上的版本中,必须使用显式的intent去执行启动服务,如果使用隐式的intent,则会报如下错误:


    错误信息

    解决办法是我们先构建一个隐式的Intent,然后通过PackageManager的resolveService获取可能会被启动的Service的信息。如果ResolveInfo不为空,说明我们能通过上面隐式的Intent找到对应的Service,并且我们还可以获取将要启动的Service的package信息以及类型。然后我们需要将根据得到的Service的包名和类名,构建一个ComponentName,从而设置intent要启动的具体的组件信息,这样intent就从隐式变成了一个显式的intent

    Intent intent = new Intent();
    intent.setAction(SERVICE_ACTION);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    
    PackageManager pm = getPackageManager();
    //我们先通过一个隐式的Intent获取可能会被启动的Service的信息
    ResolveInfo info = pm.resolveService(intent, 0);
    if(info != null){
      //如果ResolveInfo不为空,说明我们能通过上面隐式的Intent找到对应的Service
      //我们可以获取将要启动的Service的package信息以及类型
      String packageName = info.serviceInfo.packageName;
      String serviceNmae = info.serviceInfo.name;
      //然后我们需要将根据得到的Service的包名和类名,构建一个ComponentName
      //从而设置intent要启动的具体的组件信息,这样intent就从隐式变成了一个显式的intent
      //之所以大费周折将其从隐式转换为显式intent,是因为从Android 5.0 Lollipop开始,
      //Android不再支持通过通过隐式的intent启动Service,只能通过显式intent的方式启动Service
      //在Android 5.0 Lollipop之前的版本倒是可以通过隐式intent启动Service
      ComponentName componentName = new ComponentName(packageName, serviceNmae);
      intent.setComponent(componentName);
      try{
        Log.i("DemoLog", "客户端调用bindService方法");
        bindService(intent, conn, BIND_AUTO_CREATE);
      }catch(Exception e){
        e.printStackTrace();
        Log.e("DemoLog", e.getMessage());
      }
    }
    

    相关文章

      网友评论

          本文标题:Android 隐式Intent

          本文链接:https://www.haomeiwen.com/subject/fnvtpqtx.html