preface

The content of this article is actually an extension of the previous article (Android Basics 5: Intents and Intent Filters). Due to the length of the article, the content of this article is not included in the previous article. This article mainly lists common implicit Intents for you. If you have relevant requirements in your daily work, you can directly copy the code to use.

This article directory

1. Operations related to alarm clocks

(1) Create an alarm

Here’s how to create an alarm clock:

1. Property Settings2. The Intent example

  • Kotlin version:
fun createAlarm(message: String, hour: Int, minutes: Int) {
    val intent = Intent(AlarmClock.ACTION_SET_ALARM).apply {
        putExtra(AlarmClock.EXTRA_MESSAGE, message)
        putExtra(AlarmClock.EXTRA_HOUR, hour)
        putExtra(AlarmClock.EXTRA_MINUTES, minutes)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
public void createAlarm(String message, int hour, int minutes) {
    Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)
            .putExtra(AlarmClock.EXTRA_MESSAGE, message)
            .putExtra(AlarmClock.EXTRA_HOUR, hour)
            .putExtra(AlarmClock.EXTRA_MINUTES, minutes);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

The required permissions

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

3. Intent – filter sample

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

The running effect is as follows:

(2) Create a timer

Here’s how to create a timer:

1. Property Settings2. The Intent example

  • Kotlin version:
fun startTimer(message: String, seconds: Int) {
    val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
        putExtra(AlarmClock.EXTRA_MESSAGE, message)
        putExtra(AlarmClock.EXTRA_LENGTH, seconds)
        putExtra(AlarmClock.EXTRA_SKIP_UI, true)}if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
public void startTimer(String message, int seconds) {
    Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
            .putExtra(AlarmClock.EXTRA_MESSAGE, message)
            .putExtra(AlarmClock.EXTRA_LENGTH, seconds)
            .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

The required permissions

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

3. Intent – filter sample

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

The running effect is as follows

The EXTRA_SKIP_UI is set to false for demo purposes.

(3) Display all alarm clocks

Not many applications call this Intent (mostly system applications), but any application with an alarm clock type should implement this Intent filter.

1. Property Settings2. The Intent example

  • Kotlin version:
fun allAlarm(a) {
        val intent = Intent(AlarmClock.ACTION_SHOW_ALARMS)
        if(intent.resolveActivity(packageManager) ! =null) {
            startActivity(intent)
        }
    }
Copy the code
  • Java version
public void allAlarm(a) {
	Intent intent = new Intent(AlarmClock.ACTION_SHOW_ALARMS);
		if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

3. Intent – filter sample

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

The running effect is as follows

Second, the calendar

To add new events to the mobile phone calendar, please refer to the following property Settings:

1. Property Settings2. The Intent example

  • Kotlin version
fun addEvent(title: String, location: String, begin: Long, end: Long) {
    val intent = Intent(Intent.ACTION_INSERT).apply {
        data = Events.CONTENT_URI
        putExtra(Events.TITLE, title)
        putExtra(Events.EVENT_LOCATION, location)
        putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin)
        putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
public void addEvent(String title, String location, long begin, long end) {
    Intent intent = new Intent(Intent.ACTION_INSERT)
            .setData(Events.CONTENT_URI)
            .putExtra(Events.TITLE, title)
            .putExtra(Events.EVENT_LOCATION, location)
            .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin)
            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

3. Intent – filter sample

<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>
Copy the code

Operation effect: calladdEvent()The test code for the method is as follows:

addEvent("Pick someone up at the airport."."International Airport", System.currentTimeMillis(), System.currentTimeMillis());
Copy the code

3. Camera-related operations

(1) Take photos or videos and return them

To open the camera and receive the captured photos or videos, use ACTION_IMAGE_CAPTURE or ACTION_VIDEO_CAPTURE. In addition, in EXTRA_OUTPUT EXTRA, you can specify the URI location to which the camera will save the photo or video.

1. Property SettingsWhen the camera successfully returns focus to the Activity (onActivityResult() callback), you can use theEXTRA_OUTPUTThe specified URI accesses a photo or video.

2. Code examples

The method of calling the camera cannot be implemented according to the practice in the Official Android document, because calling the camera will involve permission application (6.0 and above system), but also involve the problem of obtaining the results of taking photos after the completion of the problem, there are great differences in the way of obtaining before and after 7.0. So if you write code the way the official documents do, you’ll find that you can’t adjust the camera at all. Permission application and camera related knowledge, we will write a separate article later. The purpose of this article is to introduce you to the use of Intents, so if you encounter code that you don’t understand, you don’t need to dive into it. Complete code examples as follows, we focus on the dispatchTakePictureIntent () method in the Intent of usage can be:

public class MainActivity extends AppCompatActivity {
    private TextView mBtnCreateAlarm;
    private ImageView mIvCapturePhoto;

    private static final int MY_PERMISSIONS_REQUEST = 0;
    private static final int REQUEST_TAKE_PHOTO = 1;

    /** * Need to use but not authorized permissions saved in this List */
    private List<String> permissionNotGrantedList = new ArrayList<>();
    private String currentPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnCreateAlarm = findViewById(R.id.btn_create_alarm);
        mIvCapturePhoto = findViewById(R.id.iv_capture_photo);

        mBtnCreateAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // In Android 6.0 and above, permissions are dynamically applied
                    checkPermission();
                } else{ dispatchTakePictureIntent(); }}}); }/** * Android 6.0 dynamic permission application */
    private void checkPermission(a) {
        // Check whether the permission has been granted and add it to the list if not
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) ! = PackageManager.PERMISSION_GRANTED) { permissionNotGrantedList.add(Manifest.permission.CAMERA); }if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ! = PackageManager.PERMISSION_GRANTED) { permissionNotGrantedList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); }if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) ! = PackageManager.PERMISSION_GRANTED) { permissionNotGrantedList.add(Manifest.permission.READ_EXTERNAL_STORAGE); }// If the list is empty, all permissions are obtained, and there is no need to obtain them again. Not empty to apply for permission
        if(! permissionNotGrantedList.isEmpty()) { ActivityCompat.requestPermissions(MainActivity.this,
                    permissionNotGrantedList.toArray(new String[permissionNotGrantedList.size()]), MY_PERMISSIONS_REQUEST);
        } else{ dispatchTakePictureIntent(); }}@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST:
                List<String> list = new ArrayList();
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if(grantResults[i] == PackageManager.PERMISSION_DENIED) { list.add(permissions[i]); }}if(list.isEmpty()) { dispatchTakePictureIntent(); }}else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            default:
                break; }}/** * Build the Intent */
    private void dispatchTakePictureIntent(a) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if(takePictureIntent.resolveActivity(getPackageManager()) ! =null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {

            }

            if(photoFile ! =null) {
                Uri photoURI;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    photoURI = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
                } else{ photoURI = Uri.fromFile(photoFile); } takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); }}}private File createImageFile(a) throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath); mIvCapturePhoto.setImageBitmap(bitmap); }}}Copy the code

Running effect

2. Start the camera application in still image mode

Launching the camera app in still image mode means jumping directly to the camera app. The photos taken are saved directly to the phone’s album, and the results are not returned to the calling Activity. The Action used to launch the camera application in still image mode is INTENT_ACTION_STILL_IMAGE_CAMERA

1. The Intent example:

  • Kotlin version
fun capturePhoto(a) {
    val intent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)
    }
}
Copy the code
  • Java version
public void capturePhoto(a) {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); }}Copy the code

2. The intent – filter sample

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

Running effect You can see that when the photo is taken, the result is directly saved to the album, and there is no button to let the user choose to reshoot or select the result.

(3) Start the camera application in video mode

The Action used to launch the camera application in video mode is INTENT_ACTION_VIDEO_CAMERA

1. The Intent example

  • Kotlin version
fun capturePhoto(a) {
    val intent = Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA)
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)
    }
}
Copy the code
  • Java version
public void capturePhoto(a) {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); }}Copy the code

2. The intent – filter sample

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

4. Contact related operations

(1) Select a contact

If you need to get a contact, use ACTION_PICK and specify the MIME type as contacts.content_type. The result of selecting a contact is a Content :URI. This action uses the Contacts Provider API to grant temporary read rights to the contact, so we don’t need to add the READ_CONTACTS rights.

1. Property Settings2. Examples of Intent

  • Kotlin version
const val REQUEST_SELECT_CONTACT = 1

fun selectContact(a) {
    val intent = Intent(Intent.ACTION_PICK).apply {
        type = ContactsContract.Contacts.CONTENT_TYPE
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivityForResult(intent, REQUEST_SELECT_CONTACT)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int.data: Intent) {
    if (requestCode == REQUEST_SELECT_CONTACT && resultCode == RESULT_OK) {
        val contactUri: Uri = data.data
        // Do something with the selected contact at contactUri
        / /...}}Copy the code
  • Java version
static final int REQUEST_SELECT_CONTACT = 1;

public void selectContact(a) {
    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. }}Copy the code

Running effect The information on how to retrieve contact details after obtaining the contact URI is not expanded here, but will be covered in a later article.

(2) Select a specific data of the contact

In the previous section, we showed how to select and get a Uri for a contact. If we need more specific information about that contact, we need to parse that Uri specifically. The benefit of this is that we can get all the information about the contact based on that Uri, but the disadvantage is that we need to write more parsing code. However, if we only need to obtain the phone number or email address of a contact (for example, to obtain the phone number of a contact, or to obtain the email address of a contact), then we can use the content in this section. Again, this action does not require the application to be granted the READ_CONTACTS permission.

1. Property Settings2. Examples of Intent

  • Kotlin version
const val REQUEST_SELECT_PHONE_NUMBER = 1

fun selectContact(a) {
    // Start an activity for the user to pick a phone number from contacts
    val intent = Intent(Intent.ACTION_PICK).apply {
        type = CommonDataKinds.Phone.CONTENT_TYPE
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int.data: Intent) {
    if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == Activity.RESULT_OK) {
        // Get the URI and query the content provider for the phone number
        val contactUri: Uri = data.data
        val projection: Array<String> = arrayOf(CommonDataKinds.Phone.NUMBER)
        contentResolver.query(contactUri, projection, null.null.null).use { cursor ->
            // If the cursor returned is valid, get the phone number
            if (cursor.moveToFirst()) {
                val numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER)
                val number = cursor.getString(numberIndex)
                // Do something with the phone number. }}}}Copy the code
  • Java version
static final int REQUEST_SELECT_PHONE_NUMBER = 1;

public void selectContact(a) {
    // 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
            / /...}}}Copy the code

Operation effect:

(3) View contacts

We can query the details of a contact based on its Uri without any application permissions.

1. Property Settings1. The Intent example

  • Kotlin version
fun viewContact(contactUri: Uri) {
    val intent = Intent(Intent.ACTION_VIEW, contactUri)
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
public void viewContact(Uri contactUri) {
    Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

Operation effect:

(4) Edit existing contacts

To edit a known contact, use the ACTION_EDIT operation, using content: URI as Intent data specified contacts, and will be designated by the constant extra any known contact information is included in the ContactsContract. The Intents. Insert. Also, no permissions are required to use the contact URI returned by ACTION_PICK.

1. Property Settings2. The Intent example

  • Kotlin version
fun editContact(contactUri: Uri, email: String) {
    val intent = Intent(Intent.ACTION_EDIT).apply {
        data = contactUri
        putExtra(ContactsContract.Intents.Insert.EMAIL, email)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

Operation effect:

(5) Insert a contact

To insert a new contact, use ACTION_INSERT, set contacts. CONTENT_TYPE to MIME, and save the contact information in Extra. The contact information of the Key keywords defined in ContactsContract. The Intents. Insert, such as ContactsContract. The Intents. Insert. NAME.

1. Property Settings2. The Intent example

  • Kotlin version
fun insertContact(name: String, email: String) {
    val intent = Intent(Intent.ACTION_INSERT).apply {
        type = ContactsContract.Contacts.CONTENT_TYPE
        putExtra(ContactsContract.Intents.Insert.NAME, name)
        putExtra(ContactsContract.Intents.Insert.EMAIL, email)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

Operation effect:

E-mail

This section describes sending email:

1. Property Settings2. The Intent example

  • Kotlin version
fun composeEmail(addresses: Array<String>, subject: String, attachment: Uri) {
    val intent = Intent(Intent.ACTION_SEND).apply {
        type = "* / *"
        putExtra(Intent.EXTRA_EMAIL, addresses)
        putExtra(Intent.EXTRA_SUBJECT, subject)
        putExtra(Intent.EXTRA_STREAM, attachment)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

If you want to ensure that the Intent is handled only by the email application (and not another SMS or social application), use the ACTION_SENDTO action and add a “mailto:” type of Data. Such as:

  • Kotlin version
fun composeEmail(addresses: Array<String>, subject: String) {
    val intent = Intent(Intent.ACTION_SENDTO).apply {
        data = Uri.parse("mailto:") // only email apps should handle this
        putExtra(Intent.EXTRA_EMAIL, addresses)
        putExtra(Intent.EXTRA_SUBJECT, subject)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

3. Intent – filter sample

<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>
Copy the code

Operation effect:

6. File storage

(1) Obtain a file of a specified type

If you need to get a document or photo from the file manager, you can use ACTION_GET_CONTENT and specify the desired MIME type. The result is the URI of the file. The URI can be of any type, HTTP: URI, File: URI, or Content: URI.

On Android 4.3 (API level 18) and later, you can also allow the user to select multiple files by adding EXTRA_ALLOW_MULTIPLE to the Intent and setting it to true. Each selected file can then be accessed in the ClipData object returned by getClipData().

1. Property Settings2. The Intent example

  • Kotlin version
const val REQUEST_IMAGE_GET = 1

fun selectImage(a) {
    val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
        type = "image/*"
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivityForResult(intent, REQUEST_IMAGE_GET)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int.data: Intent) {
    if (requestCode == REQUEST_IMAGE_GET && resultCode == Activity.RESULT_OK) {
        val thumbnail: Bitmap = data.getParcelableExtra("data")
        val fullPhotoUri: Uri = data.data
        // Do work with photo saved at fullPhotoUri. }}Copy the code
  • Java version
static final int REQUEST_IMAGE_GET = 1;

public void selectImage(a) {
    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. }}Copy the code

Operation effect: Of course, you can also support multiple choices:

static final int REQUEST_IMAGE_GET = 1;

    public void selectImage(a) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        // On Android 4.3 (API level 18) and later
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        }

        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) {
            ClipData clipData = data.getClipData();
            if(clipData ! =null) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item itemAt = clipData.getItemAt(i);
                    Uri uri = itemAt.getUri();
                    stringBuilder.append(uri + "\n"); } textView.setText(stringBuilder); }}}Copy the code

(2) Open a file of a specific type

When running on Android 4.4 or later, you can use ACTION_OPEN_DOCUMENT instead of ACTION_GET_CONTENT.

1. Property Settings2. The Intent example

  • Kotlin version
const val REQUEST_IMAGE_OPEN = 1

fun selectImage2(a) {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        type = "image/*"
        addCategory(Intent.CATEGORY_OPENABLE)
    }
    // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
    startActivityForResult(intent, REQUEST_IMAGE_OPEN)
}

override fun onActivityResult(requestCode: Int, resultCode: Int.data: Intent) {
    if (requestCode == REQUEST_IMAGE_OPEN && resultCode == Activity.RESULT_OK) {
        val fullPhotoUri: Uri = data.data
        // Do work with full size photo saved at fullPhotoUri. }}Copy the code
  • Java version
static final int REQUEST_IMAGE_OPEN = 1;

public void selectImage(a) {
    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. }}Copy the code

Seven, telephone

To open the phone application and dial a phone number, use ACTION_DIAL and specify the phone number using the URI schema defined below. The phone app displays phone numbers when opened, but users must press the call button to start a call.

To make a call directly, use ACTION_CALL and specify the phone number using the URI schema defined below. When the phone app is open, it makes a call without the user having to press the call button.

The ACTION_CALL action requires you to add CALL_PHONE rights to the manifest file:

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

1. Property Settings2. The Intent example

  • Kotlin version
fun dialPhoneNumber(phoneNumber: String) {
    val intent = Intent(Intent.ACTION_DIAL).apply {
        data = Uri.parse("tel:$phoneNumber")}if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

Operation effect:

Eight, search,

(a) Use application-specific search

To support searching within your own application environment, declare an Intent filter in your application using the SEARCH_ACTION action, as shown in the following Intent filter example:

<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>
Copy the code

(2) Use web search

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

1. Property Settings2. The Intent example

  • Kotlin version
fun searchWeb(query: String) {
    val intent = Intent(Intent.ACTION_WEB_SEARCH).apply {
        putExtra(SearchManager.QUERY, query)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
public void searchWeb(String query) {
    Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
    intent.putExtra(SearchManager.QUERY, query);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

Operation effect:

Nine, set

To open a system setup page, use one of the following intents:

  • 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

The Intent of sample

  • Kotlin version
fun openWifiSettings(a) {
    val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
public void openWifiSettings(a) {
    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
    if(intent.resolveActivity(getPackageManager()) ! =null) { startActivity(intent); }}Copy the code

Operation effect:

Send text messages

To initiate an SMS or MMS, use one of the following Intences and use the following extra keys to specify message details such as phone number, subject, and message body.

1. Property Settings2. The Intent example

  • Kotlin version
fun composeMmsMessage(message: String, attachment: Uri) {
    val intent = Intent(Intent.ACTION_SENDTO).apply {
        type = HTTP.PLAIN_TEXT_TYPE
        putExtra("sms_body", message)
        putExtra(Intent.EXTRA_STREAM, attachment)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

If you want to ensure that the Intent is handled only by the SMS application (and not other email or social applications), then use the ACTION_SENDTO action and add the “SMSTO :” data architecture. Such as:

  • Kotlin version
fun composeMmsMessage(message: String, attachment: Uri) {
    val intent = Intent(Intent.ACTION_SEND).apply {
        data = Uri.parse("smsto:")  // This ensures only SMS apps respond
        putExtra("sms_body", message)
        putExtra(Intent.EXTRA_STREAM, attachment)
    }
    if(intent.resolveActivity(packageManager) ! =null) {
        startActivity(intent)
    }
}
Copy the code
  • Java version
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); }}Copy the code

2. The intent – filter sample

<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>
Copy the code

Reference documentation: General Intent