• Android开发学习之Intent具体解释


    Intent简单介绍和具体解释:
             
    Intent:协助应用间的交互与通信,Intent负责相应用中一次操作的动作。动作涉及的数据。附加数据进行描写叙述。      
            ndroid则依据此Intent的描写叙述,负责找到相应的组件,将 Intent传递给调用的组件,并完毕组件的调用。
            Intent不仅可用于应用程序之间,也可用于应用程序内部的Activity/Service之间的交互。因此,能够将Intent理解为不同组件之间通信的“媒介”专门提供组件互相调用的相关信息。



    Intent启动组件的方法:
        
        1.启动Activity:   激活一个新的Activity,或者让一个现有的Activity做新的操作
                       Context.startActivity(Intent intent)
                       Context.startActivityForResutle(Intent intent)
        2.启动Service:启动一个新的Service,或者向一个已有的Service传递新的指令
                       Context.startService(Intent intent)
                       Context.bindService(Intent intent)
        3.启动Broadcast:发送Broadcast Intent。发送之后,全部已注冊的而且拥有与之相匹配IntentFilter的BroadcastReceiver就会被激活。 
                       Context.sendBroadcast()
                       Context.sendOrderedBoradcast()
                       Context.sendStickyBroadcast()
         
         注:Intent一旦发出,Android都会准确找到相匹配的一个或多个Activity,Service或者BroadcastReceiver做出响应,
             不同类型的Intent消息不会出现重叠,即Broadcast的Intent消息仅仅会发送给BroadcastReceiver,而决不会发送给Activity或者Service。


             由startActivity()传递的消息也仅仅会发给Activity。由startService()传递的Intent仅仅会发送给Service。



    Intent的几个属性:

      动作(Action),数据(Data),分类(Category),类型(Type),组件(Compent)以及扩展信(Extra)。

    当中最经常使用的是Action属性和Data属性。


    1.Action属性:指Intent要完毕的动作,是一个字符串常量,Android的SDK中定义了一些系统动作常量。
                  如打电话,发短信,编辑。查询等动作常量


    一些经常使用的Action:

    ACTION_CALL activity 启动一个电话.
    ACTION_EDIT activity 显示用户编辑的数据.
    ACTION_MAIN activity 作为Task中第一个Activity启动
    ACTION_SYNC activity 同步手机与数据server上的数据.
    ACTION_BATTERY_LOW broadcast receiver 电池电量过低警告.
    ACTION_HEADSET_PLUG broadcast receiver 插拔耳机警告
    ACTION_SCREEN_ON broadcast receiver 屏幕变亮警告.
    ACTION_TIMEZONE_CHANGED broadcast receiver 改变时区警告.


      应用:
      1.通过Intent对象调用系统的拨号动作
      Intent i = new Intent(Intent.ACTION_DIAL,Uri.parse(”tel://13800138000″));
     startActivity(i);
      2.通过Intent对象调用系统的获取联系人动作
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_GET_CONTENT);
      intent.setType("com.android.cursor.item/phone");// 设置Intent Type 属性 ,主要是获取通讯录的内容  
      startActivity(intent);


    2.Intent的Data属性
    Intent的Data属性是运行动作的URI和MIME类型,不同的Action有不同的Data数据指定。比方:ACTION_EDIT Action应该和要编辑的文档URI Data匹配。ACTION_VIEW应用应该和要显示的URI匹配。


    3.Intent的Category属性
    Intent中的Category属性是一个运行动作Action的附加信息。


    如:CATEGORY_HOME表示回Home界面,ALTERNATIVE_CATEGORY表示当前的Intent是一系列的可选动作中的一个

    另解:一个字符串。包括了关于处理该intent的组件的种类的信息。一个intent对象能够有随意个category。intent类定义了很多category常数.

    addCategory()方法为一个intent对象添加一个category,
    removeCategory删除一个category,
    getCategories()获取intent全部的category.


    应用:回到Home界面的样例
    btn = (Button)findViewById(R.id.Button1);  
    btn.setOnClickListener(new OnClickListener() {  
        @Override 
        public void onClick(View v) {     
            Intent intent = new Intent();                 
            intent.setAction(Intent.ACTION_MAIN);// 加入Action属性                
            intent.addCategory(Intent.CATEGORY_HOME);// 加入Category属性              
            startActivity(intent);// 启动Activity  
        }  
    });  


    4.Intent的Extra属性:加入一些组件的简单附加信息
       1.在Extra中放置信息:
       //设置Intent的class属性,跳转到SecondActivity  
    intent.setClass(FirstActivity.this, SecondActivity.class);  
    //为intent加入额外的信息  
    intent.putExtra("useName", etx.getText().toString());  
    //启动Activity  
    startActivity(intent); 
        2.获取Extra中的附加信息
        //获得Intent  
        Intent intent = this.getIntent();         
        tv = (TextView)findViewById(R.id.TextView1);  
        //从Intent获得额外信息。设置为TextView的文本  
        tv.setText(intent.getStringExtra("useName"));  


    5.用Intent调用系统中经常使用的组件:
            1 ,web浏览器
      Uri uri = Uri. parse ( "http://www.google.com" );

      returnIt = new Intent (Intent . ACTION_VIEW , uri );


      2,地图
      Uri mapUri = Uri. parse ( "geo:38.899533,-77.036476" );

      returnIt = new Intent (Intent . ACTION_VIEW , mapUri);


      3,调拨打电话界面
      Uri telUri = Uri. parse ( "tel:100861" );

      returnIt = new Intent (Intent . ACTION_DIAL , telUri);


      4,直接拨打电话
      Uri callUri = Uri. parse ( "tel:100861" );

      returnIt = new Intent (Intent . ACTION_CALL , callUri);


      5。卸载
      Uri uninstallUri = Uri. fromParts ( "package" , " xxx " , null );

      returnIt = new Intent (Intent . ACTION_DELETE , uninstallUri);


      6,安装
      Uri installUri = Uri. fromParts ( "package" , " xxx " , null );

      returnIt = new Intent (Intent . ACTION_PACKAGE_ADDED , installUri);


      7,播放

      Uri playUri = Uri. parse ( "file:///sdcard/download/everything.mp3" );

      returnIt = new Intent (Intent . ACTION_VIEW , playUri);


      8,掉用发邮件
      Uri emailUri = Uri. parse ( "mailto:shenrenkui@gmail.com" );

      returnIt = new Intent (Intent . ACTION_SENDTO , emailUri);


         9。发邮件
      returnIt = new Intent (Intent . ACTION_SEND );
      String[] tos = { "shenrenkui@gmail.com" };
      String[] ccs = { "shenrenkui@gmail.com" };
      returnIt .putExtra(Intent . EXTRA_EMAIL , tos);
      returnIt .putExtra(Intent . EXTRA_CC , ccs);
      returnIt .putExtra(Intent . EXTRA_TEXT , "body" );
      returnIt .putExtra(Intent . EXTRA_SUBJECT , "subject" );
      returnIt .setType( "message/rfc882" );

      Intent . createChooser ( returnIt , "Choose Email Client" );


      10,发短信
      Uri smsUri = Uri. parse ( "tel:100861" );
      returnIt = new Intent (Intent . ACTION_VIEW , smsUri);
      returnIt.putExtra( "sms_body" , "shenrenkui" );

      returnIt.setType( "vnd.android -dir/mms-sms" );


      11,直接发邮件
      Uri smsToUri = Uri. parse ( "smsto://100861" );
      returnIt = new Intent (Intent . ACTION_SENDTO , smsToUri);

      returnIt.putExtra( "sms_body" , "shenrenkui" );


      12,发彩信
      Ur i mmsUri = Uri. parse ( "content://media/external/images/media/23" );
      returnIt = new Intent (Intent . ACTION_SEND );
      returnIt.putExtra( "sms_body" , "shenrenkui" );
      returnIt.putExtra(Intent . EXTRA_STREAM , mmsUri);

      returnIt.setType( "image/png" );


      Intent的动画
      void, overridePendingTransition (int enterAnim, int exitAnim).
      在startActivity(Intent) or finish()的时候调用。


    Intent的构造函数:
    公共构造函数:

    1、Intent() 空构造函数


    2、Intent(Intent o) 拷贝构造函数


    3、Intent(String action) 指定action类型的构造函数


    4、Intent(String action, Uri uri) 指定Action类型和Uri的构造函数,URI主要是结合程序之间的数据共享ContentProvider


    5、Intent(Context packageContext, Class<?> cls) 传入组件的构造函数,也就是上文提到的


    6、Intent(String action, Uri uri, Context packageContext, Class<?> cls) 前两种结合体


    Intent有六种构造函数,3、4、5是最经常使用的
    Intent(String action, Uri uri)  的action就是相应在AndroidMainfest.xml中的action节点的name属性值。在Intent类中定义了非常多的Action和Category常量。


    应用:
       1: Intent intent = new Intent(Intent.ACTION_EDIT, null);
       2: startActivity(intent);


    这里用了第四种构造函数,仅仅是uri參数为null。

    运行此代码的时候。系统就会在程序主配置文件AndroidMainfest.xml中寻找
    <action android:name="android.intent.action.EDIT" />相应的Activity。
    假设相应为多个activity具有<action android:name="android.intent.action.EDIT" />此时就会弹出一个dailog选择Activity。




    利用Intent在Activity之间传递数据
    在Main中运行例如以下代码:


       1: Bundle bundle = new Bundle();


       2: bundle.putStringArray("NAMEARR", nameArr);


       3: Intent intent = new Intent(Main.this, CountList.class);


       4: intent.putExtras(bundle);


       5: startActivity(intent);


    在CountList中,代码例如以下:


       1: Bundle bundle = this.getIntent().getExtras();


       2: String[] arrName = bundle.getStringArray("NAMEARR");



    Intent的解析:


    在应用中,我们能够以两种形式来使用Intent:

    1.1 显式Intent:指定了component属性的Intent(调用setComponent(ComponentName)或者setClass(Context, Class)来指定)。

    通过指定详细的组件类,通知应用启动相应的组件。


    2.2 隐式Intent:没有指定comonent属性的Intent。

    这些Intent须要包括足够的信息。这样系统才干依据这些信息,在在全部的可用组件中,确定满足此Intent的组件。
    对于直接Intent,Android不须要去做解析。由于目标组件已经非常明白,Android须要解析的是那些间接Intent,通过解析将 Intent映射给能够处理此Intent的Activity、Service或Broadcast Receiver。
    Intent解析机制
    Intent解析机制主要是通过查找已注冊在AndroidManifest.xml中的全部<intent-filter>及当中定义的Intent,通过PackageManager(注:PackageManager可以得到当前设备上所安装的
    application package的信息)来查找能处理这个Intent的component。

    在这个解析过程中,Android是通过Intent的action、type、category这三个属性来进行推断的。推断方法例如以下:
    1.1  假设Intent指明定了action,则目标组件的IntentFilter的action列表中就必须包括有这个action,否则不能匹配;
    1.2  假设Intent没有提供type,系统将从data中得到数据类型。和action一样。目标组件的数据类型列表中必须包括Intent的数据类型,否则不能匹配。
    1.3  假设Intent中的数据不是content:类型的URI,并且Intent也没有明白指定type,将依据Intent中数据的scheme(比方 http:或者mailto:)进行匹配。同上,Intent 的scheme必须出如今目标组件的scheme列表中。


    1.4 假设Intent指定了一个或多个category,这些类别必须所有出如今组建的类别列表中。比方Intent中包括了两个类别:LAUNCHER_CATEGORY和ALTERNATIVE_CATEGORY,解析得到的目标组件必须至少包括这两个类别。




    Intent启动组件的方法

    Intent能够启动一个Activity,也能够启动一个Service,还能够发起一个广播Broadcasts。详细方法例如以下:

    组件名称

    方法名称

     

    Activity

    startActvity( )

    startActivity( )

     

    Service

    startService( )

    bindService( )

     

    Broadcasts

    sendBroadcasts( )

    sendOrderedBroadcasts( )

    sendStickyBroadcasts( )

    三.Intent的属性

    Intent有下面几个属性:

    动作(Action),数据(Data),分类(Category),类型(Type),组件(Compent)以及扩展信(Extra)。

    当中最经常使用的是Action属性和Data属性。

    1.Intent的Action属性

    Action是指Intent要完毕的动作,是一个字符串常量。

    SDK中定义了一些标准的Action常量例如以下表所看到的。

    Constant

    Target component

    Action

    ACTION_CALL

    activity

    Initiate a phone call.

    ACTION_EDIT

    activity

    Display data for the user to edit.

    ACTION_MAIN

    activity

    Start up as the initial activity of a task, with no data input and no returned output.

    ACTION_SYNC

    activity

    Synchronize data on a server with data on the mobile device.

    ACTION_BATTERY_LOW

    broadcast receiver

    A warning that the battery is low.

    ACTION_HEADSET_PLUG

    broadcast receiver

    A headset has been plugged into the device, or unplugged from it.

    ACTION_SCREEN_ON

    broadcast receiver

    The screen has been turned on.

    ACTION_TIMEZONE_CHANGED

    broadcast receiver

    The setting for the time zone has changed.

     以下是一个測试Action常量的样例:

    main.xml

    复制代码
    <?

    xml version="1.0" encoding="utf-8"?

    > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:text="測试Action属性" android:id="@+id/getBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

    复制代码

     strings.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <string name="hello">測试Action属性</string> 
        <string name="app_name">IntentActionDemo</string> 
    </resources> 

    MainActivity.java

    复制代码
    public class MainActivity extends Activity {  
        private Button getBtn;  
        @Override 
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
              
            getBtn=(Button)findViewById(R.id.getBtn);  
            getBtn.setOnClickListener(new OnClickListener() {  
                @Override 
                public void onClick(View v) {     
                    Intent intent = new Intent();                 
                    intent.setAction(Intent.ACTION_GET_CONTENT);// 设置Intent Action属性                  
                    intent.setType("vnd.android.cursor.item/phone");// 设置Intent Type 属性   
                                                                    //主要是获取通讯录的内容  
                    startActivity(intent); // 启动Activity  
                }  
            });          
        }  
    } 
    复制代码

    效果图:

    2.Intent的Data属性

    Intent的Data属性是运行动作的URI和MIME类型,不同的Action有不同的Data数据指定。

    比方:ACTION_EDIT Action应该和要编辑的文档URI Data匹配,ACTION_VIEW应用应该和要显示的URI匹配。

    3.Intent的Category属性

    Intent中的Category属性是一个运行动作Action的附加信息。

    比方:CATEGORY_HOME则表示放回到Home界面。ALTERNATIVE_CATEGORY表示当前的Intent是一系列的可选动作中的一个。

    下表是SDK文档中关于Category的信息。

     

    Constant

    Meaning

    CATEGORY_BROWSABLE

    The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message.

    CATEGORY_GADGET

    The activity can be embedded inside of another activity that hosts gadgets.

    CATEGORY_HOME

    The activity displays the home screen, the first screen the user sees when the device is turned on or when the HOME key is pressed.

    CATEGORY_LAUNCHER

    The activity can be the initial activity of a task and is listed in the top-level application launcher.

    CATEGORY_PREFERENCE

    The target activity is a preference panel.

     

     以下是一个回到Home界面的样例:

    main.xml

    复制代码
    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:orientation="vertical" android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        >     
        <TextView   
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"   
        android:text="測试Intent Category"   
        /> 
        <Button   
        android:id="@+id/Button1"   
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"   
        android:text="转到Home界面" 
        />    
    </LinearLayout> 
    复制代码

    strings.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <string name="hello">Hello World, MainActivity!</string> 
        <string name="app_name">IntentCategoryDemo</string> 
    </resources> 

    MainActivity.java

    复制代码
    package com.android.category.activity;  
     
    import android.app.Activity;  
    import android.content.Intent;  
    import android.os.Bundle;  
    import android.view.View;  
    import android.view.View.OnClickListener;  
    import android.widget.Button;  
     
    public class MainActivity extends Activity {  
        private Button btn;  
        @Override 
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
              
            btn = (Button)findViewById(R.id.Button1);  
            btn.setOnClickListener(new OnClickListener() {  
                @Override 
                public void onClick(View v) {     
                    Intent intent = new Intent();                 
                    intent.setAction(Intent.ACTION_MAIN);// 加入Action属性                
                    intent.addCategory(Intent.CATEGORY_HOME);// 加入Category属性              
                    startActivity(intent);// 启动Activity  
                }  
            });  
        }  
    } 
    复制代码

     效果图:

     

     

    4.Intent的Type属性

    Intent的Type属性显式指定Intent的数据类型(MIME)。一般Intent的数据类型可以依据数据本身进行判定。可是通过设置这个属性,可以强制採用显式指定的类型而不再进行推导。


     

    5.Intent的Compent属性

    Intent的Compent属性指定Intent的的目标组件的类名称。通常 Android会依据Intent 中包括的其他属性的信息,比方action、data/type、category进行查找,终于找到一个与之匹配的目标组件。

    可是。假设 component这个属性有指定的话,将直接使用它指定的组件,而不再运行上述查找过程。指定了这个属性以后,Intent的其他全部属性都是可选的。

     6.Intent的Extra属性

    Intent的Extra属性是加入一些组件的附加信息。比方。假设我们要通过一个Activity来发送一个Email,就能够通过Extra属性来加入subject和body。

     以下的样例在第一个Activity的EditText输入username,该年龄保存在Intent的Extras属性中。当单击Button时。会在第二个Activity中显示username。

    first.xml

    复制代码
    <?xml version="1.0" encoding="utf-8"?

    > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请输入username" /> <EditText android:id="@+id/EditText1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測试Extras属性" /> </LinearLayout>

    复制代码

    second.xml

    复制代码
    <?

    xml version="1.0" encoding="utf-8"?

    > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/TextView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

    复制代码

    strings.xml

    <?

    xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, FirstActivity!</string> <string name="app_name">IntentExtrasDemo</string> </resources>

    FirstActivity.java

     

    复制代码
    public class FirstActivity extends Activity {  
        private Button btn;  
        private EditText etx;  
          
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.first);  
              
            btn = (Button)findViewById(R.id.Button1);  
            etx = (EditText)findViewById(R.id.EditText1);  
              
            btn.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                    Intent intent = new Intent();  
                    //设置Intent的class属性。跳转到SecondActivity  
                    intent.setClass(FirstActivity.this, SecondActivity.class);  
                    //为intent加入额外的信息  
                    intent.putExtra("useName", etx.getText().toString());  
                    //启动Activity  
                    startActivity(intent);  
                }  
            });         
        }  
    } 
    复制代码

    SecondActivity.java

    复制代码
    public class SecondActivity extends Activity {  
        private TextView tv;  
          
        @Override 
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            //设置当前的Activity的界面布局  
            setContentView(R.layout.second);  
            //获得Intent  
            Intent intent = this.getIntent();         
            tv = (TextView)findViewById(R.id.TextView1);  
            //从Intent获得额外信息,设置为TextView的文本  
            tv.setText(intent.getStringExtra("useName"));  
        }  
    } 
    复制代码

    注意:在加入第二个Activity SecondActivity的时候,要在AndroidManifest.xml里面加入上SecondActivity。详细例如以下。即是在15行</activity>的后面加入上16~18行的代码。假设不这样做,就会在模拟器上出现错误。

    复制代码
    <?xml version="1.0" encoding="utf-8"?> 
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="com.android.extras.activity" 
          android:versionCode="1" 
          android:versionName="1.0"> 
        <uses-sdk android:minSdkVersion="10" /> 
     
        <application android:icon="@drawable/icon" android:label="@string/app_name"> 
            <activity android:name=".FirstActivity" 
                      android:label="@string/app_name"> 
                <intent-filter> 
                    <action android:name="android.intent.action.MAIN" /> 
                    <category android:name="android.intent.category.LAUNCHER" /> 
                </intent-filter> 
            </activity> 
            <activity android:name=".SecondActivity" 
                      android:label="@string/app_name"> 
            </activity> 
        </application> 
    </manifest> 
    复制代码

    效果图:


  • 相关阅读:
    决定Java程序员工资高低的三个因素
    Java常见面试题汇总(七)
    Java的 RMI与RPC的区别
    2019新版Java学习路径
    JAVA中String,StringBuilder以及StringBuffer三个类之间的区别
    2019Java开发学习路线图
    bzoj1458 士兵占领
    bzoj1303 [CQOI2009]中位数图
    bzoj3721 [PA2014 Final] Bazarek
    bzoj2659 [Beijing wc2012]算不出的算式
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5238139.html
Copyright © 2020-2023  润新知