What is an Intent in Android?
Intent is an object used to communicate with different Android Components like Activity, Services, BroadcastReceiver etc. Intent is used for navigation and data transfer between components.
There are two types of Intent:
- Implicit Intent - System finds suitable component (e.g., open URL, camera)
- Explicit Intent - You specify exact component class (e.g., MainActivity to SecondActivity)
Implicit Intent Examples
1. Open URL in Browser
Intent in = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://deepsingh44.blogspot.com/"));
startActivity(in);
2. Open Camera
Intent openCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(openCamera, CAMERA_PIC_REQUEST);
3. Open Gallery to Choose Image
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select image to upload"), CHOOSE_FILE);
4. Dial Phone Number (Opens Dialer)
Intent in = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:" + "Phone_Number"));
startActivity(in);
No permission needed for ACTION_DIAL - it only opens dialer.
5. Direct Call
Intent in = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + "Phone_Number"));
startActivity(in);
Permission Required in AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
6. Send Email
Intent email = new Intent(Intent.ACTION_SENDTO);
email.setData(Uri.parse("mailto:xyz@gmail.com"));
startActivity(Intent.createChooser(email, "Send Enquiry..."));
7. Share Content (Text)
Intent si = new Intent(Intent.ACTION_SEND);
si.setType("text/plain");
String body = "Something wants to share...";
si.putExtra(Intent.EXTRA_SUBJECT, "Subject");
si.putExtra(Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(si, "Share via"));
8. Send SMS
Intent sms = new Intent(Intent.ACTION_VIEW);
sms.setType("vnd.android-dir/mms-sms");
sms.putExtra("address", "receiver_phone_number_here");
sms.putExtra("sms_body", "Message Here...");
startActivity(sms);
Explicit Intent Example
Explicit Intent is used to navigate from one Activity to another Activity within same app. You must specify destination class.
// From MainActivity to SecondActivity
Intent in = new Intent(getApplicationContext(), SecondActivity.class);
// Or: Intent in = new Intent(MainActivity.this, SecondActivity.class);
startActivity(in);
Difference:
Implicit: Intent(Action, Data) → System decides which app can handle it
Explicit: Intent(Context, TargetClass) → You decide which Activity to open
Implicit: Intent(Action, Data) → System decides which app can handle it
Explicit: Intent(Context, TargetClass) → You decide which Activity to open
Conclusion
Use Implicit Intent to use other apps' features (camera, browser, dialer). Use Explicit Intent for internal navigation and passing data via putExtra(). Always handle permissions for CALL, CAMERA etc.
No comments:
Post a Comment