Android Intent usage summary

Android provides Intent mechanism to assist in the interaction and communication between applications, Intent responsible for the operation of the application in one operation, action involving data, additional data are described, Android is based on this Intent description, responsible for finding corresponding components, will Intent passed to the calling component, and complete the call to the component. Intent can be used not only between applications, can also be used for interaction between internal applications Activity / Service. Therefore, Intent here plays a role of the media intermediary that specializes in providing information on component called each other to achieve decoupling between the caller and the callee.

image

1. Intent role

Intent is an abstract description of an action to be performed, it is generally used as a parameter, the Intent to assist with the communication between the various components Android. For example, calling startActivity () to start an Activity, or be delivered by broadcaseIntent () to BroadcaseReceiver all interested, and then, or to start a background service by startService () / bindservice (). It can be seen, Intent is used to start the main activity or other service, the intent can be understood as an adhesive between the activity.

Intent form of action is:

  • Start Activity

Activity by a start Context.startActvity () / Activity.startActivityForResult ();

  • Start Service

Start by Context.startService () a service, or by Context.bindService () and back-office service interaction;

  • Send Broadcast

Broadcast Receivers distributed by a broadcast method Context.sendBroadcasts () / Context.sendOrderedBroadcast () / Context.sendStickyBroadcast ()

2. Intent species

  • Explicit Intent

Explicit, i.e. corresponding to the activity directly specifies class needs to open.

1) constructor passing Component, the most common way:

Intent intent = new Intent(this, SecondActivity.class);  
startActivity(intent);  

2) setComponent method

Intent intent = new Intent();    
intent.setClass(this, SecondActivity.class);  
//或者intent.setClassName(this, "com.example.app.SecondActivity");  
//或者intent.setClassName(this.getPackageName(),"com.example.app.SecondActivity");            
startActivity(intent);

3) setClass / setClassName Method

Intent intent = new Intent();    
intent.setClass(this, SecondActivity.class);  
//或者intent.setClassName(this, "com.example.app.SecondActivity");  
//或者intent.setClassName(this.getPackageName(),"com.example.app.SecondActivity");            
startActivity(intent);  

Intent explicitly set the Activity class may need to call directly by Component, can uniquely identify Activity, intent particularly clear, so explicit. Setting this manner may be class Class object (e.g. SecondActivity.class), may be added to the string name of the class name (e.g., "com.example.app.SecondActivity") package.

  • Implicit Intent

Implicitly, not explicitly specify which Activity to start, but set the Action, Data, Category, allow the system to filter out the appropriate Activity. Screening is based on all To screen.

Below Action, for example:

AndroidManifest.xml file, there must first be called Activity with a And contains The Activity, setting Intent can handle, and the category is set to "android.intent.category.DEFAULT". The name is a string action, can be customized, for example, assumed here to become "mark":

<activity  
    android:name="com.example.app.SecondActivity">  
    <intent-filter>  
        <action android:name="mark"/>  
        <category android:name="android.intent.category.DEFAULT"/>  
    </intent-filter>  
</activity>  

Then, in MainActivity, you can find top Activity by the action name. The following two methods are provided by setAction Action and construction methods, the same effects in two ways.

1) setAction method

Intent intent = new Intent();  
intent.setAction("mark");  
startActivity(intent);

2) Action constructor directly

Intent intent = new Intent("mark");  
startActivity(intent);

In order to prevent mutual influence between applications, generally naming names + Action is the package name, for example, here named "mark" is very unreasonable, it should be changed to "com.example.app.Test".

3. Intent property

Intent object generally comprises seven attributes: Action (Action), Data (data), Category (category), Type (type of data), Component (component), Extra (extended information), Flag (flag). The most commonly used is the Data property and Action property.

  • Action: action to show intent

A string variable, classes can be used to specify the action to be performed Intent. Common action are:

Activity Actions:

Types of effect
ACTION_MAIN It represents the program entry
ACTION_VIEW Data is automatically displayed in the most appropriate manner
ACTION_EDIT Provided that can be edited
ACTION_PICK Selecting a one Data, and returns it
ACTION_DAIL Data points displayed number on the dial interface Dailer
ACTION_CALL Data pointed to dial the number
ACTION_SEND Data is sent to the designated place
ACTION_SENDTO Data is sent to multiple groups designated place
ACTION_RUN Run Data, no matter what is Data
ACTION_SEARCH Perform a search
ACTION_WEB_SEARCH Perform online search
ACRION_SYNC Perform a Data Synchronization
ACTION_INSERT Add items to an empty vessel

Broadcast Actions:

Types of effect
ACTION_TIME_TICK Change the current time, and real-time transmission time can only be sent through the system. Call format "android.intent.action.TIME_TICK"
ACTION_TIME_CHENGED Set the time. Call format "android.intent.action.TIME_SET"
  • Data: data indicating the operation to be manipulated

URI object is a manifestation of a reference data, or data MIME type; type of data is determined by the action Intent.

  • Category: performance categories for action

Intent string containing additional information indicating what type of components to handle the Intent. Any number of Category description can be added to the Intent, but does not require a lot of intent category, the following are some common category:

Types of effect
CATEGORY_DEFAULT The set may be a component Component implicit started
CATEGORY_LAUNCHER The action is set in a top-level execution. And this attribute icon comprising Activity defined the substituents defined application icon
CATEGORY_BROWSABLE When the network-related Intent point, you must add this category
CATEGORY_HOME Intent point to the Home screen
CATEGORY_PREFERENCE Activity is the definition of a preference pane Preference Panel
  • Type: Specifies the type of data

Intent general data type can be determined based on the data itself, but by setting this property, can force the specified type explicit derivation instead.

  • Component: The purpose components

Intent designated target component name, when the attribute is specified, the system will skip other attributes match, the matching property to directly start the corresponding components.

  • Extra: Extended Information

Additional key-value data Intent can carry, you can set the data by calling putExtra () method, each key corresponds to a data value. You can also store all the data by creating a Bundle object, and then set the data by calling putExtras () method.

Types of effect
EXTRA_BCC Storing email address string array Bcc
EXTRA_CC E-mail addresses stored carbon copy of an array of strings
EXTRA_EMAIL Store the e-mail address of an array of strings
EXTRA_SUBJECT Storing the message subject string
EXTRA_TEXT Storing message content
EXTRA_KEY_EVENT KeyEvent way to store objects trigger button Intent
EXTRA_PHONE_ NUMBER Phone number stored calls ACTION_CALL

Flag: the intent of the desired operating mode

Is used to indicate how the system starts a Activity, flag labels can be used in the Intent by setFlags () or addFlags ().

Types of effect
FLAG_ACTIVITY_CLEAR_TOP Equivalent SingleTask
FLAGE_ACTIVITY_SINGLE_TOP Equivalent SingleTop
FLAG_ACTIVITY_NEW_TASK Similar SingleInstance
FLAG_ACTIVITY_NO_HISTORY After leaving the Activity, the Activity will be removed from the task stack

4. Intent usage

Call dialer

// 调用拨打电话,给10010拨打电话
Uri uri = Uri.parse("tel:10010");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
// 直接拨打电话,需要加上权限 <uses-permission id="android.permission.CALL_PHONE" /> 
Uri callUri = Uri.parse("tel:10010"); 
Intent intent = new Intent(Intent.ACTION_CALL, callUri); 

Send SMS or MMS

 // 给10010发送内容为“Hello”的短信
Uri uri = Uri.parse("smsto:10010");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello");
startActivity(intent);
// 发送彩信(相当于发送带附件的短信)
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);

Open the web browser

// 打开百度主页
Uri uri = Uri.parse("https://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

send email

// 给[email protected]发邮件
Uri uri = Uri.parse("mailto:[email protected]");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(intent);
// 给[email protected]发邮件发送内容为“Hello”的邮件
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "[email protected]");
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 = {"[email protected]", "[email protected]"}; // 收件人
String[] ccs = {"[email protected]", "[email protected]"}; // 抄送
String[] bccs = {"[email protected]", "[email protected]"}; // 密送
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);

Show map and route planning

 // 打开Google地图中国北京位置(北纬39.9,东经116.3)
Uri uri = Uri.parse("geo:39.9,116.3");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
// 路径规划:从北京某地(北纬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);

Play multimedia

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/foo.mp3");
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

Select Image

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 2);

Photograph

// 打开拍照程序
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
 // 取出照片数据
Bundle extras = intent.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
获取并剪切图片
// 获取并剪切图片
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);

Open the phone application market

// 打开手机应用市场,直接进入该程序的详细页面
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

Setup

String fileName = Environment.getExternalStorageDirectory() + "/myApp.apk";   
Intent intent = new Intent(Intent.ACTION_VIEW);   
intent.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");   
startActivity(intent);

Uninstaller

Uri uri = Uri.parse("package:" + packageName);   
Intent intent = new Intent(Intent.ACTION_DELETE, uri);
startActivity(intent);
进入设置界面
// 进入系统设置界面
Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
startActivity(intent);

Guess you like

Origin www.cnblogs.com/linhaostudy/p/12244446.html