美文网首页
【基础笔记】Intent的初步使用

【基础笔记】Intent的初步使用

作者: 究极无敌棒棒糖 | 来源:发表于2019-12-26 11:35 被阅读0次

    一、Intent

    An intent is an abstract description of an operation to be performed. It can be used with Context#startActivity(Intent) to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and Context.startService(Intent) or Context.bindService(Intent, ServiceConnection, int) to communicate with a background Service.
    Intent-Android Developers


    二、Intent的分类

    • 显式Intent:

    Intent有多个构造函数的重载,其中一个是Intent(Context packageContext, Class<?>cls),第一个参数Context 要求提供一个启动活动的上下文,第二个参数Class 则是指定想要启动的目标活动使用。
    通过startActivity(Intent)方式来启动活动,Intent的“意图”非常明显,称之为显式Intent

    • 隐式Intent:

    隐式Intent并不明确指出我们想要启动哪一个活动,而是指定了一系列更为抽象的action 和category 等信息,然后交由系统去分析这个Intent,并帮我们找出合适的活动去启动。


    三、Intent的属性

    Intent对象大致包括7大属性:Action(动作)Data(数据)Category(类别)Type(数据类型)Component(组件)Extra(扩展信息)Flag(标志位)

    1、主要属性(Action,Data,category

    • Action

    The general action to be performed
    用来表现意图的行动的一个字符串变量,可以用来指定Intent要执行的动作类别。

    1、Standard Activity Actions

    动作名称 作用
    ACTION_MAIN 表示程序入口
    ACTION_VIEW 自动以最合适的方式显示Data
    ACTION_EDIT 提供可以编辑的
    ACTION_PICK 选择一个一条Data,并且返回它
    ACTION_DAIL 显示Data指向的号码在拨号界面Dailer上
    ACTION_CALL 拨打Data指向的号码
    ACTION_SEND 发送Data到指定的地方
    ACTION_SENDTO 发送多组Data到指定的地方
    ACTION_RUN 运行Data,不管Data是什么
    ACTION_SEARCH 执行搜索
    ACTION_WEB_SEARCH 执行网上搜索
    ACRION_SYNC 执同步一个Data
    ACTION_INSERT 添加一个空的项到容器中

    2、Standard Broadcast Actions

    动作名称 作用
    ACTION_TIME_TICK 当前时间改变,并即时发送时间,只能通过系统发送。调用格式"android.intent.action.TIME_TICK"
    ACTION_TIME_CHENGED 设置时间。调用格式"android.intent.action.TIME_SET"
    • Data

    The data to operate on, such as a person record in the contacts database, expressed as a Uri
    表示与动作要操纵的数据。一个URI对象是一个引用的data的表现形式,或是data的MIME类型;data的类型由Intent的action决定。

    • Categories

    Gives additional information about the action to execute. For example, CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level application, while CATEGORY_ALTERNATIVE means it should be included in a list of alternative actions the user can perform on a piece of data.
    方法addCategory(String)
    用来表现动作的类别。一个包含Intent额外信息的字符串,表示哪种类型的组件来处理这个Intent。任何数量的Category 描述都可以添加到Intent中,但是很多intent不需要category(默认为Default),下面列举一些常用的category:

    类型 作用
    CATEGORY_DEFAULT 把一个组件Component设为可被implicit启动的
    CATEGORY_LAUNCHER 把一个action设置为在顶级执行。并且包含这个属性的Activity所定义的icon将取代application中定义的icon
    CATEGORY_BROWSABLE 当Intent指向网络相关时,必须要添加这个类别
    CATEGORY_HOME 使Intent指向Home界面
    CATEGORY_PREFERENCE 定义的Activity是一个偏好面板Preference Panel

    2、次要属性(TypeComponentExtraFlag

    • Type

    Specifies an explicit type (a MIME type) of the intent data. Normally the type is inferred from the data itself. By setting this attribute, you disable that evaluation and force an explicit type
    指定数据类型。 显示的指定Intent的数据类型,而跳过了通过Uri进行推导判断的步骤。如:Vedio、Image、Voice等。

    • Component

    Specifies an explicit name of a component class to use for the intent. Normally this is determined by looking at the other information in the intent (the action, data/type, and categories) and matching that with a component that can handle it. If this attribute is set then none of the evaluation is performed, and this component is used exactly as is. By specifying this attribute, all of the other Intent attributes become optional.
    目的组件。 指定Intent的目标组件名称,当指定了这个属性后,系统将跳过匹配其他属性,而直接匹配这个属性来启动对应的组件。

    • Extra

    This is a Bundle of any additional information. This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc.
    扩展信息。Intent可以携带的额外 key-value 数据,你可以通过调用putExtra()方法设置数据,每一个 key对应一个 value数据。你也可以通过创建 Bundle对象来存储所有数据,然后通过调用putExtras()方法来设置数据。

    类型 作用
    EXTRA_BCC 存放邮件密送人地址的字符串数组
    EXTRA_CC 存放邮件抄送人地址的字符串数组
    EXTRA_EMAIL 存放邮件地址的字符串数组
    EXTRA_SUBJECT 存放邮件主题字符串
    EXTRA_TEXT 存放邮件内容
    EXTRA_KEY_EVENT 以KeyEvent对象方式存放触发Intent 的按键
    EXTRA_PHONE_ NUMBER 存放调用ACTION_CALL 时的电话号码
    • Flag
      意图的运行模式。用来指示系统如何启动一个Activity,可以通过setFlags()或者addFlags()可以把标签flag用在Intent中。
    类型 作用
    FLAG_ACTIVITY_CLEAR_TOP 相当于SingleTask
    FLAGE_ACTIVITY_SINGLE_TOP 相当于SingleTop
    FLAG_ACTIVITY_NEW_TASK 类似于SingleInstance
    FLAG_ACTIVITY_NO_HISTORY 当离开该Activity后,该Activity将被从任务栈中移除

    三、Intent的常用方法

    1、构造方法:

    Intent(Intent intent); //通过复制一个Intent来创建一个新的Intent
    Intent(String action); //构造一个指定action的Intent对象
    Intent(String action,Uri uri); //构造一个指定action,并且有指向数据的uri的Intent对象
    Intent(Context packageContext,Clsaa<?>class); //构造一个有指定Component属性的Intent
    

    2、常用方法:

    addCategory(String Category); //添加一条Category属性
    addFlags(int Flags); //添加一条Flag标签
    clone(); //复制一个Object类型的对象
    getExtras(); //获得一个Bundle对象
    getSourceBounds(); //获得发送Intent的组件的边界坐标
    makeMainActivity(ComponentName mainActivity); //创建一个Category属性为luancher的Intent去启动mainActivity
    parseUri(String uri,int flags) //通过解析一个uri获得一个Intent对象
    setComponent(); //添加component属性
    setClass(); //相当于添加component属性
    setClassName(); //相当于添加component属性
    resolveActivity(PackageManager); //解析Intent启动的Activity,返回ComponentName对象
    createChooser(Intent target,CharSequence title);// 创建一个有选择对话框的Intent
    setDataAndType(Uri data,  String type)//Uri类型的data和Mime类型的type
    setData();setType();
    getData();getType();//设置/获得Data/Type类型的数据
    

    3、在AndroidManifest中配置:

    通过在<activity> 标签下配置<intent-filter> 的内容,可以指定当前活动能够响应的action 和category

    <activity android:name=".SecondActivity" >
                <intent-filter>
                    <action android:name="com.example.activitytest.ACTION_START" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="com.example.activitytest.MY_CATEGORY"/>
                    <data android:scheme="http"/>
                </intent-filter>
            </activity>
    

    可以在<intent-filter> 标签中再配置一个<data> 标签,用于更精确地指定当前活动能够响应什么类型的数据。<data> 标签中主要可以配置以下内容。

    • android:scheme 。用于指定数据的协议部分,如http。
    • android:host 。用于指定数据的主机名部分,如www.baidu.com
    • android:port 。用于指定数据的端口部分,一般紧随在主机名之后。
    • android:path 。用于指定主机名和端口之后的部分,如一段网址中跟在域名之后的内容。
    • android:mimeType 。用于指定可以处理的数据类型,允许使用通配符的方式进行指定。

    四、常用系统Intent合集

    // 调用拨打电话,给10010拨打电话
    //===============================================================
    //1.拨打电话
    // 给移动客服10086拨打电话
    Uri uri = Uri.parse("tel:10086");
    Intent intent = new Intent(Intent.ACTION_DIAL, uri);
    startActivity(intent);
     
    //===============================================================
     
    //2.发送短信
    // 给10086发送内容为“Hello”的短信
    Uri uri = Uri.parse("smsto:10086");
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    intent.putExtra("sms_body", "Hello");
    startActivity(intent);
     
    //3.发送彩信(相当于发送带附件的短信)
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra("sms_body", "Hello");
    Uri uri = Uri.parse("content://media/external/images/media/23");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.setType("image/png");
    startActivity(intent);
     
    //===============================================================
     
    //4.打开浏览器:
    // 打开百度主页
    Uri uri = Uri.parse("http://www.baidu.com");
    Intent intent  = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
     
    //===============================================================
     
    //5.发送电子邮件:(阉割了Google服务的没戏!!!!)
    // 给someone@domain.com发邮件
    Uri uri = Uri.parse("mailto:someone@domain.com");
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    startActivity(intent);
    // 给someone@domain.com发邮件发送内容为“Hello”的邮件
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, "someone@domain.com");
    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    intent.putExtra(Intent.EXTRA_TEXT, "Hello");
    intent.setType("text/plain");
    startActivity(intent);
    // 给多人发邮件
    Intent intent=new Intent(Intent.ACTION_SEND);
    String[] tos = {"1@abc.com", "2@abc.com"}; // 收件人
    String[] ccs = {"3@abc.com", "4@abc.com"}; // 抄送
    String[] bccs = {"5@abc.com", "6@abc.com"}; // 密送
    intent.putExtra(Intent.EXTRA_EMAIL, tos);
    intent.putExtra(Intent.EXTRA_CC, ccs);
    intent.putExtra(Intent.EXTRA_BCC, bccs);
    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    intent.putExtra(Intent.EXTRA_TEXT, "Hello");
    intent.setType("message/rfc822");
    startActivity(intent);
     
    //===============================================================
     
    //6.显示地图:
    // 打开Google地图中国北京位置(北纬39.9,东经116.3)
    Uri uri = Uri.parse("geo:39.9,116.3");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
     
    //===============================================================
     
    //7.路径规划
    // 路径规划:从北京某地(北纬39.9,东经116.3)到上海某地(北纬31.2,东经121.4)
    Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=39.9 116.3&daddr=31.2 121.4");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
     
    //===============================================================
     
    //8.多媒体播放:
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.parse("file:///sdcard/foo.mp3");
    intent.setDataAndType(uri, "audio/mp3");
    startActivity(intent);
     
    //获取SD卡下所有音频文件,然后播放第一首=-= 
    Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
     
    //===============================================================
     
    //9.打开摄像头拍照:
    // 打开拍照程序
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    startActivityForResult(intent, 0);
    // 取出照片数据
    Bundle extras = intent.getExtras(); 
    Bitmap bitmap = (Bitmap) extras.get("data");
     
    //另一种:
    //调用系统相机应用程序,并存储拍下来的照片
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    time = Calendar.getInstance().getTimeInMillis();
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
    .getExternalStorageDirectory().getAbsolutePath()+"/tucue", time + ".jpg")));
    startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE);
     
    //===============================================================
     
    //10.获取并剪切图片
    // 获取并剪切图片
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.putExtra("crop", "true"); // 开启剪切
    intent.putExtra("aspectX", 1); // 剪切的宽高比为1:2
    intent.putExtra("aspectY", 2);
    intent.putExtra("outputX", 20); // 保存图片的宽和高
    intent.putExtra("outputY", 40); 
    intent.putExtra("output", Uri.fromFile(new File("/mnt/sdcard/temp"))); // 保存路径
    intent.putExtra("outputFormat", "JPEG");// 返回格式
    startActivityForResult(intent, 0);
    // 剪切特定图片
    Intent intent = new Intent("com.android.camera.action.CROP"); 
    intent.setClassName("com.android.camera", "com.android.camera.CropImage"); 
    intent.setData(Uri.fromFile(new File("/mnt/sdcard/temp"))); 
    intent.putExtra("outputX", 1); // 剪切的宽高比为1:2
    intent.putExtra("outputY", 2);
    intent.putExtra("aspectX", 20); // 保存图片的宽和高
    intent.putExtra("aspectY", 40);
    intent.putExtra("scale", true);
    intent.putExtra("noFaceDetection", true); 
    intent.putExtra("output", Uri.parse("file:///mnt/sdcard/temp")); 
    startActivityForResult(intent, 0);
     
    //===============================================================
     
    //11.打开Google Market 
    // 打开Google Market直接进入该程序的详细页面
    Uri uri = Uri.parse("market://details?id=" + "com.demo.app");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
     
    //===============================================================
     
    //12.进入手机设置界面:
    // 进入无线网络设置界面(其它可以举一反三)  
    Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);  
    startActivityForResult(intent, 0);
     
    //===============================================================
     
    //13.安装apk:
    Uri installUri = Uri.fromParts("package", "xxx", null);   
    returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
     
    //===============================================================
     
    //14.卸载apk:
    Uri uri = Uri.fromParts("package", strPackageName, null);      
    Intent it = new Intent(Intent.ACTION_DELETE, uri);      
    startActivity(it); 
     
    //===============================================================
     
    //15.发送附件:
    Intent it = new Intent(Intent.ACTION_SEND);      
    it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");      
    it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3");      
    sendIntent.setType("audio/mp3");      
    startActivity(Intent.createChooser(it, "Choose Email Client"));
     
    //===============================================================
     
    //16.进入联系人页面:
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(People.CONTENT_URI);
    startActivity(intent);
     
    //===============================================================
     
     
    //17.查看指定联系人:
    Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, info.id);//info.id联系人ID
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(personUri);
    startActivity(intent);
     
    //===============================================================
     
    //18.调用系统编辑添加联系人(高版本SDK有效):
    Intent it = newIntent(Intent.ACTION_INSERT_OR_EDIT);    
    it.setType("vnd.android.cursor.item/contact");    
    //it.setType(Contacts.CONTENT_ITEM_TYPE);    
    it.putExtra("name","myName");    
    it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY, "organization");    
    it.putExtra(android.provider.Contacts.Intents.Insert.EMAIL,"email");    
    it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone");    
    it.putExtra(android.provider.Contacts.Intents.Insert.SECONDARY_PHONE,"mobilePhone");    
    it.putExtra( android.provider.Contacts.Intents.Insert.TERTIARY_PHONE,"workPhone");    
    it.putExtra(android.provider.Contacts.Intents.Insert.JOB_TITLE,"title");    
    startActivity(it);
     
    //===============================================================
     
    //19.调用系统编辑添加联系人(全有效):
    Intent intent = newIntent(Intent.ACTION_INSERT_OR_EDIT);    
    intent.setType(People.CONTENT_ITEM_TYPE);    
    intent.putExtra(Contacts.Intents.Insert.NAME, "My Name");    
    intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");    
    intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE,Contacts.PhonesColumns.TYPE_MOBILE);    
    intent.putExtra(Contacts.Intents.Insert.EMAIL, "com@com.com");    
    intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, Contacts.ContactMethodsColumns.TYPE_WORK);    
    startActivity(intent);
     
    //===============================================================
     
    //20.打开另一程序 
    Intent i = new Intent();     
    ComponentName cn = new ComponentName("com.example.jay.test",     
    "com.example.jay.test.MainActivity");     
    i.setComponent(cn);     
    i.setAction("android.intent.action.MAIN");     
    startActivityForResult(i, RESULT_OK);
     
    //===============================================================
     
    //21.打开录音机
    Intent mi = new Intent(Media.RECORD_SOUND_ACTION);     
    startActivity(mi);
     
    //===============================================================
     
    //22.从google搜索内容 
    Intent intent = new Intent();     
    intent.setAction(Intent.ACTION_WEB_SEARCH);     
    intent.putExtra(SearchManager.QUERY,"searchString")     
    startActivity(intent);
     
    //===============================================================
     
    

    相关文章

      网友评论

          本文标题:【基础笔记】Intent的初步使用

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