Android 之常见Intent

介绍

    英文水平不错的请直接参考官方文档:https://developer.android.com/guide/components/intents-common.html

    An intent allows you to start an activity in another app by describing a simple action you'd like to perform (such as "view a map" or "take a picture") in an Intent object. This type of intent is called an implicit intent because it does not specify the app component to start, but instead specifies an action and provides some data with which to perform the action.

    Intent允许你通过一个描述你想执行的动作(比如“查看地图”或是“拍照”)的Intent对象打开其他应用的activity,这种intent被称为隐式Intent,以为它没有指定要启动某个具体的应用组建,而是指定一个“动作”并提供一些数据以执行这个动作。

    When you call startActivity() or startActivityForResult() and pass it an implicit intent, the system resolves the intent to an app that can handle the intent and starts its corresponding Activity. If there's more than one app that can handle the intent, the system presents the user with a dialog to pick which app to use.

    当你调用 startActivity() 或 startActivityForResult() 并提供一个隐式的Intent的时候,系统会启动能处理这个Intent的应用的Activity。如果有多个这样的Activity,系统会提供一个可以让用户自己选择要使用的应用的对话框。

    This page describes several implicit intents that you can use to perform common actions, organized by the type of app that handles the intent. Each section also shows how you can create an intent filter to advertise your app's ability to perform the same action.

    本文会介绍一些执行常用动作的隐式Intent。每个部分也会演示怎么创建一个Intent过滤器来处理一些动作。

    Caution: If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

    下面就逐一介绍。

Alarm Clock(时钟)

    设定闹钟

    Note: Only the hour, minutes, and message extras are available in Android 2.3 (API level 9) and higher. The other extras were added in later versions of the platform.

    注意:只有hour, minutes, 和 message参数可以在android2.3及以上使用,其他的是之后的版本才添加进来的。

    描述:

    Action:ACTION_SET_ALARM

    Data URI:None

    MIME Type:None

    Extras:

  •     EXTRA_HOUR:小时
  •     EXTRA_MINUTES:分钟
  •     EXTRA_MESSAGE:自定义消息
  •     EXTRA_DAYS:An ArrayList including each week day on which this alarm should be repeated. Each day must be declared with an integer from the Calendar class such as MONDAY. For a one-time alarm, do not specify this extra.
  •     EXTRA_RINGTONE:A content: URI specifying a ringtone to use with the alarm, or VALUE_RINGTONE_SILENT for no ringtone. To use the default ringtone, do not specify this extra.
  •     EXTRA_VIBRATE:A boolean specifying whether to vibrate for this alarm.
  •     EXTRA_SKIP_UI:A boolean specifying whether the responding app should skip its UI when setting the alarm. If true, the app should bypass any confirmation UI and simply set the specified alarm.

    例子:

    /**
     * 设置闹钟
     * @param context 这个不用说了吧
     * @param msg 闹钟标题
     * @param hour 时
     * @param min 分
     */
    public static void createAlarm(Context context, String msg, int hour, int min){
        Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
        intent.putExtra(AlarmClock.EXTRA_MESSAGE,msg);
        intent.putExtra(AlarmClock.EXTRA_HOUR,hour);
        intent.putExtra(AlarmClock.EXTRA_MINUTES,min);
        if(intent.resolveActivity(context.getPackageManager())!=null)
            context.startActivity(intent);
    }

    调用该函数并传入对应参数即可进入新建闹钟的activity。

    这里记得添加对应权限:

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SET_ALARM" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

    创建定时器

    创建定时器使用ACTION_SET_TIMER。

    Note: This intent was added in Android 4.4 (API level 19).

    注意:仅在android4.4及以上可以使用

    描述:

    Action:ACTION_SET_TIMER

    Data URI:None

    MIME Type:None

    Extras:

  •     EXTRA_LENGTH:The length of the timer in seconds.
  •     EXTRA_MESSAGE:A custom message to identify the timer.
  •     EXTRA_SKIP_UI:A boolean specifying whether the responding app should skip its UI when setting the timer. If true, the app should bypass any confirmation UI and simply start the specified timer.

    例子:

    /**
     * 设置计时器
     * @param context 上下文
     * @param msg 消息
     * @param sec 时间(秒)
     * @param ui true为后台计时(通常通知栏会有提示),false会弹出计时界面
     */
    public static void startTimer(Context context,String msg,int sec,boolean ui) throws SdkException {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER);
            intent.putExtra(AlarmClock.EXTRA_LENGTH,sec);
            intent.putExtra(AlarmClock.EXTRA_MESSAGE,msg);
            intent.putExtra(AlarmClock.EXTRA_SKIP_UI,ui);
            if(intent.resolveActivity(context.getPackageManager())!=null)
                context.startActivity(intent);
        }
        else throw new SdkException("SDK版本不能低于" + android.os.Build.VERSION_CODES.KITKAT);
    }

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SET_TIMER" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

    列出所有闹钟

    使用ACTION_SHOW_ALARMS。

    Note: This intent was added in Android 4.4 (API level 19).

    注意:仅在android4.4及以上可以使用。

    描述:

    Action:ACTION_SHOW_ALARMS

    Data URI:None

    MIME Type:None

    例子:

    /**
     * 显示所有闹钟
     * @param context 上下文
     * @throws SdkException
     */
    public static void showAllAlarm(Context context) throws SdkException {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(AlarmClock.ACTION_SHOW_ALARMS);
            if (intent.resolveActivity(context.getPackageManager()) != null)
                context.startActivity(intent);
        }
        else throw new SdkException("SDK版本不能低于" + android.os.Build.VERSION_CODES.KITKAT);
    }

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SHOW_ALARMS" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Calendar(日历)

    添加(日历)事件

    描述:

    Action:ACTION_INSERT

    Data URI:Events.CONTENT_URI

    MIME Type:"vnd.android.cursor.dir/event"

    Extras:

  •     EXTRA_EVENT_ALL_DAY:A boolean specifying whether this is an all-day event.
  •     EXTRA_EVENT_BEGIN_TIME:The start time of the event (milliseconds since epoch).
  •     EXTRA_EVENT_END_TIME:The end time of the event (milliseconds since epoch).
  •     TITLE:The event title.
  •     DESCRIPTION:The event description.
  •     EVENT_LOCATION:The event location.
  •     EXTRA_EMAIL:A comma-separated list of email addresses that specify the invitees.

    Many more event details can be specified using the constants defined in the CalendarContract.EventsColumns class.

    例子:

    /**
     * 添加日历事件
     * @param context 上下文
     * @param title 标题
     * @param location 位置
     * @param begin 开始
     * @param end 结束
     */
    public static void addCalenderEvent(Context context, String title, String location, Calendar begin, Calendar end) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
                .setData(CalendarContract.Events.CONTENT_URI)
                .putExtra(CalendarContract.Events.TITLE, title)
                .putExtra(CalendarContract.Events.EVENT_LOCATION, location)
                .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin)
                .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(2016,3,8,8,30);
Calendar endCalendar = Calendar.getInstance();
endCalendar.set(2016,3,8,8,30);
IntentUtils.addCalenderEvent(MainActivity.this,"title","location",startCalendar,endCalendar);

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.INSERT" />
        <data android:mimeType="vnd.android.cursor.dir/event" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Camera(相机)

    捕捉图像或视频并返回

    描述:

    Action:ACTION_IMAGE_CAPTURE or ACTION_VIDEO_CAPTURE

    Data URI Scheme:None

    MIME Type:None

    Extras:

  •     EXTRA_OUTPUT:The URI location where the camera app should save the photo or video file (as a Uri object).

    When the camera app successfully returns focus to your activity (your app receives the onActivityResult() callback), you can access the photo or video at the URI you specified with the EXTRA_OUTPUT value.

    Note: When you use ACTION_IMAGE_CAPTURE to capture a photo, the camera may also return a downscaled copy (a thumbnail) of the photo in the result Intent, saved as a Bitmap in an extra field named "data".

    注意:...

    例子:

static final int REQUEST_IMAGE_CAPTURE = 1;
static final Uri mLocationForPhotos;
public void capturePhoto(String targetFilename) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.withAppendedPath(mLocationForPhotos, targetFilename));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        // Do other work with full size photo saved in mLocationForPhotos
        ...
    }
}

    For more information about how to use this intent to capture a photo, including how to create an appropriate Uri for the output location, read Taking Photos Simply or Taking Videos Simply.

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.media.action.IMAGE_CAPTURE" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

    When handling this intent, your activity should check for the EXTRA_OUTPUT extra in the incoming Intent, then save the captured image or video at the location specified by that extra and call setResult() with an Intent that includes a compressed thumbnail in an extra named "data".

    以照相模式启动相机

    描述:

    Action:INTENT_ACTION_STILL_IMAGE_CAMERA

    Data URI Scheme:None

    MIME Type:None

    Extras:None

    例子:

public void capturePhoto() {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

    以录像模式启动相机

    描述:

    Action:INTENT_ACTION_VIDEO_CAMERA

    Data URI Scheme:None

    MIME Type:None

    Extras:None

    例子:

public void capturePhoto() {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.media.action.VIDEO_CAMERA" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Contacts(通讯录)

    选择联系人

    Tip: If you need access to only a specific piece of contact information, such as a phone number or email address, instead see the next section about how to select specific contact data.

    提示:如果你只需要选取某一具体信息(如电话号码或邮箱地址),请看下面的例子:选择联系人具体数据。

    描述:

    Action:ACTION_PICK

    Data URI Scheme:None

    MIME Type:Contacts.CONTENT_TYPE

    例子:

static final int REQUEST_SELECT_CONTACT = 1;
public void selectContact() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_SELECT_CONTACT);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_SELECT_CONTACT && resultCode == RESULT_OK) {
        Uri contactUri = data.getData();
        // Do something with the selected contact at contactUri
        ...
    }
}

    For information about how to retrieve contact details once you have the contact URI, read Retrieving Details for a Contact. Remember, when you retrieve the contact URI with the above intent, you do not need the READ_CONTACTS permission to read details for that contact.

    选择联系人具体数据

    描述:

    Action:ACTION_PICK

    Data URI Scheme:None

    MIME Type:

  •     CommonDataKinds.Phone.CONTENT_TYPE:Pick from contacts with a phone number.
  •     CommonDataKinds.Email.CONTENT_TYPE:Pick from contacts with an email address.
  •     CommonDataKinds.StructuredPostal.CONTENT_TYPE:Pick from contacts with a postal address.
  •     更多类型请参考ContactsContract类。

    例子:

static final int REQUEST_SELECT_PHONE_NUMBER = 1;
public void selectContact() {
    // Start an activity for the user to pick a phone number from contacts
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
        // Get the URI and query the content provider for the phone number
        Uri contactUri = data.getData();
        String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
        Cursor cursor = getContentResolver().query(contactUri, projection,
                null, null, null);
        // If the cursor returned is valid, get the phone number
        if (cursor != null && cursor.moveToFirst()) {
            int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
            String number = cursor.getString(numberIndex);
            // Do something with the phone number
            ...
        }
    }
}

    查看联系人

    To display the details for a known contact, use the ACTION_VIEW action and specify the contact with a content: URI as the intent data.

    There are primarily two ways to initially retrieve the contact's URI:

  •     Use the contact URI returned by the ACTION_PICK, shown in the previous section (this approach does not require any app permissions).
  •     Access the list of all contacts directly, as described in Retrieving a List of Contacts (this approach requires the READ_CONTACTS permission).

    描述:

    Action:ACTION_VIEW

    Data URI Scheme:content:<URI>

    MIME Type:None. The type is inferred from contact URI.

    例子:

public void viewContact(Uri contactUri) {
    Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    编辑一个已经存在的联系人

    To edit a known contact, use the ACTION_EDIT action, specify the contact with a content: URI as the intent data, and include any known contact information in extras specified by constants in ContactsContract.Intents.Insert.

    There are primarily two ways to initially retrieve the contact URI:

  •     Use the contact URI returned by the ACTION_PICK, shown in the previous section (this approach does not require any app permissions).
  •     Access the list of all contacts directly, as described in Retrieving a List of Contacts (this approach requires the READ_CONTACTS permission).

    描述:

    Action:ACTION_EDIT

    Data URI Scheme:content:<URI>

    MIME Type:The type is inferred from contact URI.

    Extras:One or more of the extras defined in ContactsContract.Intents.Insert so you can populate fields of the contact details.

    例子:

public void editContact(Uri contactUri, String email) {
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setData(contactUri);
    intent.putExtra(Intents.Insert.EMAIL, email);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    添加一个联系人

    To insert a new contact, use the ACTION_INSERT action, specify Contacts.CONTENT_TYPE as the MIME type, and include any known contact information in extras specified by constants in ContactsContract.Intents.Insert.

    描述:

    Action:ACTION_INSERT

    Data URI Scheme:None

    MIME Type:Contacts.CONTENT_TYPE

    Extras:One or more of the extras defined in ContactsContract.Intents.Insert.

    例子:

public void insertContact(String name, String email) {
    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setType(Contacts.CONTENT_TYPE);
    intent.putExtra(Intents.Insert.NAME, name);
    intent.putExtra(Intents.Insert.EMAIL, email);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    For more information about how to insert a contact, read Modifying Contacts Using Intents.

邮件

    写一封带附件的邮件

    描述:

    Action:

  •     ACTION_SENDTO (for no attachment) or
  •     ACTION_SEND (for one attachment) or
  •     ACTION_SEND_MULTIPLE (for multiple attachments)

    Data URI Scheme:None

    MIME Type

  •     "text/plain"
  •     "*/*"

    Extras:

  •     Intent.EXTRA_EMAIL:A string array of all "To" recipient email addresses.
  •     Intent.EXTRA_CC:A string array of all "CC" recipient email addresses.
  •     Intent.EXTRA_BCC:A string array of all "BCC" recipient email addresses.
  •     Intent.EXTRA_SUBJECT:A string with the email subject.
  •     Intent.EXTRA_TEXT A string with the body of the email.
  •     Intent.EXTRA_STREAM:A Uri pointing to the attachment. If using the ACTION_SEND_MULTIPLE action, this should instead be an ArrayList containing multiple Uri objects.

    例子:

public void composeEmail(String[] addresses, String subject, Uri attachment) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("*/*");
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_STREAM, attachment);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <data android:type="*/*" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SENDTO" />
        <data android:scheme="mailto" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

文件存储

    检索特定类型的文件

    To request that the user select a file such as a document or photo and return a reference to your app, use the ACTION_GET_CONTENT action and specify your desired MIME type. The file reference returned to your app is transient to your activity's current lifecycle, so if you want to access it later you must import a copy that you can read later. This intent also allows the user to create a new file in the process (for example, instead of selecting an existing photo, the user can capture a new photo with the camera).

    The result intent delivered to your onActivityResult() method includes data with a URI pointing to the file. The URI could be anything, such as an http: URI, file: URI, or content: URI. However, if you'd like to restrict selectable files to only those that are accessible from a content provider (a content: URI) and that are available as a file stream with openFileDescriptor(), you should add the CATEGORY_OPENABLE category to your intent.

    On Android 4.3 (API level 18) and higher, you can also allow the user to select multiple files by adding EXTRA_ALLOW_MULTIPLE to the intent, set to true. You can then access each of the selected files in a ClipData object returned by getClipData().

    描述:

    Action:ACTION_GET_CONTENT

    Data URI Scheme:None

    MIME Type:The MIME type corresponding to the file type the user should select.

    Extras:

  •     EXTRA_ALLOW_MULTIPLE:A boolean declaring whether the user can select more than one file at a time.
  •     EXTRA_LOCAL_ONLY:A boolean that declares whether the returned file must be available directly from the device, rather than requiring a download from a remote service.

    Category (optional):

  •     CATEGORY_OPENABLE:To return only "openable" files that can be represented as a file stream with openFileDescriptor().

    例子(获取照片):

static final int REQUEST_IMAGE_GET = 1;
public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_GET);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        Uri fullPhotoUri = data.getData();
        // Do work with photo saved at fullPhotoUri
        ...
    }
}

    过滤器示例(返回照片):

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />
        <data android:type="image/*" />
        <category android:name="android.intent.category.DEFAULT" />
        <!-- The OPENABLE category declares that the returned file is accessible
             from a content provider that supports OpenableColumns
             and ContentResolver.openFileDescriptor() -->
        <category android:name="android.intent.category.OPENABLE" />
    </intent-filter>
</activity>

    打开一个特定类型的文件

    Instead of retrieving a copy of a file that you must import to your app (by using the ACTION_GET_CONTENT action), when running on Android 4.4 or higher, you can instead request to open a file that's managed by another app by using the ACTION_OPEN_DOCUMENT action and specifying a MIME type. To also allow the user to instead create a new document that your app can write to, use the ACTION_CREATE_DOCUMENT action instead. For example, instead of selecting from existing PDF documents, the ACTION_CREATE_DOCUMENT intent allows users to select where they'd like to create a new document (within another app that manages the document's storage)—your app then receives the URI location of where it can write the new document.

    Whereas the intent delivered to your onActivityResult() method from the ACTION_GET_CONTENT action may return a URI of any type, the result intent from ACTION_OPEN_DOCUMENT and ACTION_CREATE_DOCUMENT always specify the chosen file as a content: URI that's backed by a DocumentsProvider. You can open the file with openFileDescriptor() and query its details using columns from DocumentsContract.Document.

    The returned URI grants your app long-term read access to the file (also possibly with write access). So the ACTION_OPEN_DOCUMENT action is particularly useful (instead of using ACTION_GET_CONTENT) when you want to read an existing file without making a copy into your app, or when you want to open and edit a file in place.

    You can also allow the user to select multiple files by adding EXTRA_ALLOW_MULTIPLE to the intent, set to true. If the user selects just one item, then you can retrieve the item from getData(). If the user selects more than one item, then getData() returns null and you must instead retrieve each item from a ClipData object that is returned by getClipData().

    Note: Your intent must specify a MIME type and must declare the CATEGORY_OPENABLE category. If appropriate, you can specify more than one MIME type by adding an array of MIME types with the EXTRA_MIME_TYPES extra—if you do so, you must set the primary MIME type in setType() to "*/*".

    描述:

    Action:

  •     ACTION_OPEN_DOCUMENT or
  •     ACTION_CREATE_DOCUMENT

    Data URI Scheme:None

    MIME Type :The MIME type corresponding to the file type the user should select.

    Extras :

  •     EXTRA_MIME_TYPES:An array of MIME types corresponding to the types of files your app is requesting. When you use this extra, you must set the primary MIME type in setType() to "*/*".
  •     EXTRA_ALLOW_MULTIPLE:A boolean that declares whether the user can select more than one file at a time.
  •     EXTRA_TITLE:For use with ACTION_CREATE_DOCUMENT to specify an initial file name.
  •     EXTRA_LOCAL_ONLY:A boolean that declares whether the returned file must be available directly from the device, rather than requiring a download from a remote service.

    Category:

  •     CATEGORY_OPENABLE:To return only "openable" files that can be represented as a file stream with openFileDescriptor().

    例子(照片):

static final int REQUEST_IMAGE_OPEN = 1;
public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
    startActivityForResult(intent, REQUEST_IMAGE_OPEN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_OPEN && resultCode == RESULT_OK) {
        Uri fullPhotoUri = data.getData();
        // Do work with full size photo saved at fullPhotoUri
        ...
    }
}

    Third party apps cannot actually respond to an intent with the ACTION_OPEN_DOCUMENT action. Instead, the system receives this intent and displays all the files available from various apps in a unified user interface.

    To provide your app's files in this UI and allow other apps to open them, you must implement a DocumentsProvider and include an intent filter for PROVIDER_INTERFACE ("android.content.action.DOCUMENTS_PROVIDER"). For example:

<provider ...
    android:grantUriPermissions="true"
    android:exported="true"
    android:permission="android.permission.MANAGE_DOCUMENTS">
    <intent-filter>
        <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
    </intent-filter>
</provider>

    For more information about how to make the files managed by your app openable from other apps, read the Storage Access Framework guide.

Local Actions(怎么翻译好呢?就附近吧)

    打车

    Note: Apps must ask for confirmation from the user before completing the action.

    描述:

    Action:ACTION_RESERVE_TAXI_RESERVATION

    Data URI:None

    MIME Type:None

    Extras:None

    例子:

public void callCar() {
    Intent intent = new Intent(ReserveIntents.ACTION_RESERVE_TAXI_RESERVATION);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="com.google.android.gms.actions.RESERVE_TAXI_RESERVATION" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

地图

    显示位置

    描述:

    Action:ACTION_VIEW

    Data URI Scheme:

  •     geo:latitude,longitude

        Show the map at the given longitude and latitude.
        Example: "geo:47.6,-122.3"

  •     geo:latitude,longitude?z=zoom

        Show the map at the given longitude and latitude at a certain zoom level. A zoom level of 1 shows the whole Earth, centered at the given lat,lng. The highest (closest) zoom level is 23.
        Example: "geo:47.6,-122.3?z=11"

  •     geo:0,0?q=lat,lng(label)

        Show the map at the given longitude and latitude with a string label.
        Example: "geo:0,0?q=34.99,-106.61(Treasure)"

  •     geo:0,0?q=my+street+address

        Show the location for "my street address" (may be a specific address or location query).
        Example: "geo:0,0?q=1600+Amphitheatre+Parkway%2C+CA"

    Note: All strings passed in the geo URI must be encoded. For example, the string 1st & Pike, Seattle should become 1st & Pike, Seattle. Spaces in the string can be encoded with %20 or replaced with the plus sign (+).

    MIME Type:None

    例子:

public void showMap(Uri geoLocation) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(geoLocation);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="geo" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

音乐和视频

    播放媒体文件

    To play a music file, use the ACTION_VIEW action and specify the URI location of the file in the intent data.

    描述:

    Action:ACTION_VIEW

    Data URI Scheme:

  •     file:<URI>
  •     content:<URI>
  •     http:<URL>

    MIME Type:

  •     "audio/*"
  •     "application/ogg"
  •     "application/x-ogg"
  •     "application/itunes"
  •     Or any other that your app may require.

    例子:

public void playMedia(Uri file) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(file);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

   过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <data android:type="audio/*" />
        <data android:type="application/ogg" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

    基于搜索播放音乐

    To play music based on a search query, use the INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH intent. An app may fire this intent in response to the user's voice command to play music. The receiving app for this intent performs a search within its inventory to match existing content to the given query and starts playing that content.

    This intent should include the EXTRA_MEDIA_FOCUS string extra, which specifies the inteded search mode. For example, the search mode can specify whether the search is for an artist name or song name.

    描述:

    Action:INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH

    Data URI Scheme:None

    MIME Type:None

    Extras:

        MediaStore.EXTRA_MEDIA_FOCUS (required):

            Indicates the search mode (whether the user is looking for a particular artist, album, song, or playlist). Most search modes take additional extras. For example, if the user is interested in listening to a particular song, the intent might have three additional extras: the song title, the artist, and the album. This intent supports the following search modes for each value of EXTRA_MEDIA_FOCUS:

            Any - "vnd.android.cursor.item/*"

                Play any music. The receiving app should play some music based on a smart choice, such as the last playlist the user listened to.

                Additional extras:

  • QUERY (required) - An empty string. This extra is always provided for backward compatibility: existing apps that do not know about search modes can process this intent as an unstructured search.

            Unstructured - "vnd.android.cursor.item/*"

                Play a particular song, album or genre from an unstructured search query. Apps may generate an intent with this search mode when they can't identify the type of content the user wants to listen to. Apps should use more specific search modes when possible.

                Additional extras:

  • QUERY (required) - A string that contains any combination of: the artist, the album, the song name, or the genre.

            Genre - Audio.Genres.ENTRY_CONTENT_TYPE

                Play music of a particular genre.

                Additional extras:

  • "android.intent.extra.genre" (required) - The genre.
  • QUERY (required) - The genre. This extra is always provided for backward compatibility: existing apps that do not know about search modes can process this intent as an unstructured search.

            Artist - Audio.Artists.ENTRY_CONTENT_TYPE

                Play music from a particular artist.

                Additional extras:

  • EXTRA_MEDIA_ARTIST (required) - The artist.
  • "android.intent.extra.genre" - The genre.
  • QUERY (required) - A string that contains any combination of the artist or the genre. This extra is always provided for backward compatibility: existing apps that do not know about search modes can process this intent as an unstructured search.

            Album - Audio.Albums.ENTRY_CONTENT_TYPE

                Play music from a particular album.

                Additional extras:

  • EXTRA_MEDIA_ALBUM (required) - The album.
  • EXTRA_MEDIA_ARTIST - The artist.
  • "android.intent.extra.genre" - The genre.
  • QUERY (required) - A string that contains any combination of the album or the artist. This extra is always provided for backward compatibility: existing apps that do not know about search modes can process this intent as an unstructured search.

            Song - "vnd.android.cursor.item/audio"

                Play a particular song.

                Additional extras:

  • EXTRA_MEDIA_ALBUM - The album.
  • EXTRA_MEDIA_ARTIST - The artist.
  • "android.intent.extra.genre" - The genre.
  • EXTRA_MEDIA_TITLE (required) - The song name.
  • QUERY (required) - A string that contains any combination of: the album, the artist, the genre, or the title. This extra is always provided for backward compatibility: existing apps that do not know about search modes can process this intent as an unstructured search.

            Playlist - Audio.Playlists.ENTRY_CONTENT_TYPE

                Play a particular playlist or a playlist that matches some criteria specified by additional extras.

                Additional extras:

  • EXTRA_MEDIA_ALBUM - The album.
  • EXTRA_MEDIA_ARTIST - The artist.
  • "android.intent.extra.genre" - The genre.
  • "android.intent.extra.playlist" - The playlist.
  • EXTRA_MEDIA_TITLE - The song name that the playlist is based on.
  • QUERY (required) - A string that contains any combination of: the album, the artist, the genre, the playlist, or the title. This extra is always provided for backward compatibility: existing apps that do not know about search modes can process this intent as an unstructured search.

    例子:

    If the user wants to listen to music from a particular artist, a search app may generate the following intent:

public void playSearchArtist(String artist) {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
    intent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS,
                    MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE);
    intent.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
    intent.putExtra(SearchManager.QUERY, artist);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

     When handling this intent, your activity should check the value of the EXTRA_MEDIA_FOCUS extra in the incoming Intent to determine the search mode. Once your activity has identified the search mode, it should read the values of the additional extras for that particular search mode. With this information your app can then perform the search within its inventory to play the content that matches the search query. For example:

protected void onCreate(Bundle savedInstanceState) {
    ...
    Intent intent = this.getIntent();
    if (intent.getAction().compareTo(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH) == 0) {
//
        String mediaFocus = intent.getStringExtra(MediaStore.EXTRA_MEDIA_FOCUS);
        String query = intent.getStringExtra(SearchManager.QUERY);
//
        // Some of these extras may not be available depending on the search mode
        String album = intent.getStringExtra(MediaStore.EXTRA_MEDIA_ALBUM);
        String artist = intent.getStringExtra(MediaStore.EXTRA_MEDIA_ARTIST);
        String genre = intent.getStringExtra("android.intent.extra.genre");
        String playlist = intent.getStringExtra("android.intent.extra.playlist");
        String title = intent.getStringExtra(MediaStore.EXTRA_MEDIA_TITLE);
//
        // Determine the search mode and use the corresponding extras
        if (mediaFocus == null) {
            // 'Unstructured' search mode (backward compatible)
            playUnstructuredSearch(query);
//
        } else if (mediaFocus.compareTo("vnd.android.cursor.item/*") == 0) {
            if (query.isEmpty()) {
                // 'Any' search mode
                playResumeLastPlaylist();
            } else {
                // 'Unstructured' search mode
                playUnstructuredSearch(query);
            }
//
        } else if (mediaFocus.compareTo(MediaStore.Audio.Genres.ENTRY_CONTENT_TYPE) == 0) {
            // 'Genre' search mode
            playGenre(genre);
//
        } else if (mediaFocus.compareTo(MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE) == 0) {
            // 'Artist' search mode
            playArtist(artist, genre);
//
        } else if (mediaFocus.compareTo(MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE) == 0) {
            // 'Album' search mode
            playAlbum(album, artist);
//
        } else if (mediaFocus.compareTo("vnd.android.cursor.item/audio") == 0) {
            // 'Song' search mode
            playSong(album, artist, genre, title);
//
        } else if (mediaFocus.compareTo(MediaStore.Audio.Playlists.ENTRY_CONTENT_TYPE) == 0) {
            // 'Playlist' search mode
            playPlaylist(album, artist, genre, playlist, title);
        }
    }
}

新的便签(New Note)

    新建便签

    To create a new note, use the ACTION_CREATE_NOTE action and specify note details such as the subject and text using extras defined below.

    Note: Apps must ask for confirmation from the user before completing the action.

    描述:

    Action:ACTION_CREATE_NOTE

    Data URI Scheme:None

    MIME Type:

  •     PLAIN_TEXT_TYPE
  •     "*/*"

    Extras:

  •     EXTRA_NAME:A string indicating the title or subject of the note.
  •     EXTRA_TEXT:A string indicating the text of the note.

    例子:

public void createNote(String subject, String text) {
    Intent intent = new Intent(NoteIntents.ACTION_CREATE_NOTE)
            .putExtra(NoteIntents.EXTRA_NAME, subject)
            .putExtra(NoteIntents.EXTRA_TEXT, text);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="com.google.android.gms.actions.CREATE_NOTE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType=”*/*”>
    </intent-filter>
</activity>

电话

    打电话

    To open the phone app and dial a phone number, use the ACTION_DIAL action and specify a phone number using the URI scheme defined below. When the phone app opens, it displays the phone number but the user must press the Call button to begin the phone call.

    To place a phone call directly, use the ACTION_CALL action and specify a phone number using the URI scheme defined below. When the phone app opens, it begins the phone call; the user does not need to press the Call button.

    The ACTION_CALL action requires that you add the CALL_PHONE permission to your manifest file:

<uses-permission android:name="android.permission.CALL_PHONE" />

    描述:

    Action:

  •     ACTION_DIAL - Opens the dialer or phone app.
  •     ACTION_CALL - Places a phone call (requires the CALL_PHONE permission)

    Data URI Scheme:

  •     tel:<phone-number>
  •     voicemail:<phone-number>

    MIME Type:None

    Valid telephone numbers are those defined in the IETF RFC 3966. Valid examples include the following:

  •     tel:2125551212
  •     tel:(212) 555 1212

    The Phone's dialer is good at normalizing schemes, such as telephone numbers. So the scheme described isn't strictly required in the Uri.parse() method. However, if you have not tried a scheme or are unsure whether it can be handled, use the Uri.fromParts() method instead.

    例子:

public void dialPhoneNumber(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.parse("tel:" + phoneNumber));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

搜索

    使用一个特定的应用搜索

    To support search within the context of your app, declare an intent filter in your app with the SEARCH_ACTION action, as shown in the example intent filter below.

    描述:

    Action:"com.google.android.gms.actions.SEARCH_ACTION",Support search queries from Google Now.

    Extras:

  •     QUERY:A string that contains the search query.

    过滤器示例:

<activity android:name=".SearchActivity">
    <intent-filter>
        <action android:name="com.google.android.gms.actions.SEARCH_ACTION"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

    web搜索

    To initiate a web search, use the ACTION_WEB_SEARCH action and specify the search string in the SearchManager.QUERY extra.

    描述:

    Action:ACTION_WEB_SEARCH

    Data URI Scheme:None

    MIME Type:None

    Extras:

  •     SearchManager.QUERY:The search string.

    例子:

public void searchWeb(String query) {
    Intent intent = new Intent(Intent.ACTION_SEARCH);
    intent.putExtra(SearchManager.QUERY, query);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

设置

    打开设置的特定选项

    To open a screen in the system settings when your app requires the user to change something, use one of the following intent actions to open the settings screen respective to the action name.

    描述:

    Action:

  •     ACTION_SETTINGS
  •     ACTION_WIRELESS_SETTINGS
  •     ACTION_AIRPLANE_MODE_SETTINGS
  •     ACTION_WIFI_SETTINGS
  •     ACTION_APN_SETTINGS
  •     ACTION_BLUETOOTH_SETTINGS
  •     ACTION_DATE_SETTINGS
  •     ACTION_LOCALE_SETTINGS
  •     ACTION_INPUT_METHOD_SETTINGS
  •     ACTION_DISPLAY_SETTINGS
  •     ACTION_SECURITY_SETTINGS
  •     ACTION_LOCATION_SOURCE_SETTINGS
  •     ACTION_INTERNAL_STORAGE_SETTINGS
  •     ACTION_MEMORY_CARD_SETTINGS

    See the Settings documentation for additional settings screens that are available.

    Data URI Scheme:None

    MIME Type:None

    例子:

public void openWifiSettings() {
    Intent intent = new Intent(Intent.ACTION_WIFI_SETTINGS);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

短信

    编写带附件的短信/彩信

    To initiate an SMS or MMS text message, use one of the intent actions below and specify message details such as the phone number, subject, and message body using the extra keys listed below.

    描述:

    Action

  •     ACTION_SENDTO or
  •     ACTION_SEND or
  •     ACTION_SEND_MULTIPLE

    Data URI Scheme:

  •     sms:<phone_number>
  •     smsto:<phone_number>
  •     mms:<phone_number>
  •     mmsto:<phone_number>

    Each of these schemes are handled the same.

    MIME Type:

  •     "text/plain"
  •     "image/*"
  •     "video/*"

    Extras:

  •     "subject":A string for the message subject (usually for MMS only).
  •     "sms_body":A string for the text message.
  •     EXTRA_STREAM:A Uri pointing to the image or video to attach. If using the ACTION_SEND_MULTIPLE action, this extra should be an ArrayList of Uris pointing to the images/videos to attach.

    例子:

public void composeMmsMessage(String message, Uri attachment) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setType(HTTP.PLAIN_TEXT_TYPE);
    intent.putExtra("sms_body", message);
    intent.putExtra(Intent.EXTRA_STREAM, attachment);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    If you want to ensure that your intent is handled only by a text messaging app (and not other email or social apps), then use the ACTION_SENDTO action and include the "smsto:" data scheme. For example:

public void composeMmsMessage(String message, Uri attachment) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setData(Uri.parse("smsto:"));  // This ensures only SMS apps respond
    intent.putExtra("sms_body", message);
    intent.putExtra(Intent.EXTRA_STREAM, attachment);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <data android:type="text/plain" />
        <data android:type="image/*" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

    Note: If you're developing an SMS/MMS messaging app, you must implement intent filters for several additional actions in order to be available as the default SMS app on Android 4.4 and higher. For more information, see the documentation at Telephony.

浏览器

    打开网址

    To open a web page, use the ACTION_VIEW action and specify the web URL in the intent data.

    描述:

    Action:ACTION_VIEW

    Data URI Scheme:

  •     http:<URL>
  •     https:<URL>

    MIME Type:

  •     "text/plain"
  •     "text/html"
  •     "application/xhtml+xml"
  •     "application/vnd.wap.xhtml+xml"

    例子:

public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

    过滤器示例:

<activity ...>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <!-- Include the host attribute if you want your app to respond
             only to URLs with your app's domain. -->
        <data android:scheme="http" android:host="www.example.com" />
        <category android:name="android.intent.category.DEFAULT" />
        <!-- The BROWSABLE category is required to get links from web pages. -->
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</activity>

    Tip: If your Android app provides functionality similar to your web site, include an intent filter for URLs that point to your web site. Then, if users have your app installed, links from emails or other web pages pointing to your web site open your Android app instead of your web page.

Verify Intents with the Android Debug Bridge

...

Intents Fired by Google Now

...

总结

    ...

你可能感兴趣的:(Android 之常见Intent)