zoukankan      html  css  js  c++  java
  • 显式Intent 和隐式 Intent 的区别

    显式 Intent :

    在知道目标组件名称的前提下,去调用Intent.setComponent()、Intent.setClassName()或Intent.setClass()方法或者在new Intent(A.this,B.class)指明需要转向到的Activity,

    显式意图明确指定了要激活的组件是哪个组件,一般是在应用程序内部使用。

    Intent intent = new Intent();
    intent.setClassName("com.android.deskclock","com.android.deskclock.DeskClock");
    startActivity(intent);

    ------------------------------------------------------------------------------

    隐式Intent:通过在清单文件中配置IntentFilter来实现的,它一般用在没有明确指出目标组件名称的前提下,当一个应用要激活另一个应用中的Activity时(看不到源代码),只能使用隐式意图,根据Activity配置的意图过滤器建一个意图,让意图中的各项参数的值都跟过滤器匹配,这样就可以激活其他应用中的Activity。Android系统会根据隐式意图中设置的动作(action)、类别(category)、数据(URI和数据类型)找到最合适的组件来处理这个意图。一般是用于在不同应用程序之间,如果想隐式intent不可以被跨应用启动只需要在AndroidManifest.xml对应的activity中配置android:exported="false"即可。

    //分享功能就是通过隐式Intent完成的。
    Intent sendIntent = new Intent();  
    sendIntent.setAction(Intent.ACTION_SEND);  
    sendIntent.putExtra(Intent.EXTRA_TEXT,"This is my text to send.");  
    sendIntent.setType("text/plain");  
    startActivity(sendIntent); 
    --------------------------------------------------------------------------
    总结:

    显示intent效率高,系统直接精确定位要启用的组件,但耦合度也高,如果通过这种方式调用一些系统组件的话,容易因为版本更新,类名、包名、包结构变化等原因导致程序崩溃。

    隐式意图能够降低程序的耦合度,但由于每次意图执行的时候,系统都会搜索所有可用的 intentfilter,来查看是否有匹配的内容,所以效率更低
    ---------------------------------------------------------------------------


    注意:

    使用隐式intent启动activity的时候如果有两个action配置是一样的,那么启动的时候系统就会弹出对话框让你选择去启动哪一个,那么怎么过滤掉自己不想启动的哪一个呢,可以自定义URL使用Scheme方式唤起Activity或App,这样就可以对同一个action进行区分了! 

    <intent-filter>
           <action android:name="android.intent.action.VIEW"></action>  
           <category android:name="android.intent.category.DEFAULT"></category>
           <category android:name="android.intent.category.BROWSABLE"></category>   
           <data
                android:scheme="app"
                android:host="test">
           </data>  
    </intent-filter>
    //隐式Intent写法为:
    Uri uri=Uri.parse("app://test");
    Intent intent=new Intent(Intent.ACTION_VIEW,uri);
    startActivity(intent);



  • 相关阅读:
    shell编程-基础
    磁盘管理-下部
    磁盘管理-中部
    磁盘管理-上部
    用户的管理
    docker之阿里云centos 7.x 启动容器报错处理办法
    IDEA之整合SVN遇到的坑(一)
    springboot之通过idea打jar包并运行
    SpringBoot整合定时任务和异步任务处理
    Microsoft SQL Server 2012安装说明
  • 原文地址:https://www.cnblogs.com/Jackie-zhang/p/10668774.html
Copyright © 2011-2022 走看看