Android Phones

Android Intent Filter with Code

Aditya Singh
Android Intent Filter with Code

An Intent Filter is an Android component that allows an app to specify the types of intents that it can handle. Intents are used to start activities, services, or broadcast receivers, and an intent filter allows an app to specify the types of intents to which it can respond.

Here is an example of an Android app that demonstrates how to use an intent filter:

// Create a new activity class
public class MyActivity extends Activity {

   // Override the onCreate() method
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_my);

      // Get the intent that started this activity
      Intent intent = getIntent();

      // Check if the intent has a specific action
      if (intent.getAction().equals(Intent.ACTION_SEND)) {
         // Handle the intent action
         // ...
      }
   }
}

This code creates an activity class and overrides the onCreate() method. In the onCreate() method, the code gets the intent that started the activity and checks if it has a specific action. If the intent has the specified action, the code handles the intent accordingly.

To specify the types of intents that this activity can handle, you can add an intent filter to the activity in the app’s AndroidManifest.xml file:

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

This code adds an intent filter to the MyActivity activity and specifies that it can handle intents with the action android.intent.action.SEND, the category android.intent.category.DEFAULT, and the MIME type text/plain. This means that the activity will only be able to handle intents that match these criteria.

To learn more about intent filters and how to use them, refer to the Android documentation: https://developer.android.com/guide/components/intents-filters.