Saturday, June 20, 2015

Android Listing App in Share Menu

The concept is really simple in Android. Just mention the mime type the app supports and from anywhere within the system when user chooses the share option, 
the application will be listed in that share option.  

<activity
   
android:name=".grid.MainActivity"
   
android:configChanges="orientation|screenSize"
   
android:label="@string/app_name" >
    <
intent-filter>
        <
action android:name="android.intent.action.SEND" />
        <
category android:name="android.intent.category.DEFAULT" />
        <
data android:mimeType="image/*" />
    </
intent-filter>
    <
intent-filter>
        <
action android:name="android.intent.action.SEND" />
        <
category android:name="android.intent.category.DEFAULT" />
        <
data android:mimeType="text/plain" />
    </
intent-filter>
    <
intent-filter>
        <
action android:name="android.intent.action.SEND_MULTIPLE" />
        <
category android:name="android.intent.category.DEFAULT" />
        <
data android:mimeType="image/*" />
    </
intent-filter>

</
activity>

Once the app is receiving the intent, below code can be used to hadle it 

Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();

if (Intent.ACTION_SEND.equals(action) && type != null) {
    if ("text/plain".equals(type)) {
        handleSendText(intent); // Handle text being sent
    } else if (type.startsWith("image/")) {
        handleSendImage(intent); // Handle single image being sent
    }
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
    if (type.startsWith("image/")) {
        handleSendMultipleImages(intent); // Handle multiple images being sent
    }
} else {
    // Handle other intents, such as being started from the home screen

}

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        // Update UI to reflect text being shared
        Toast.makeText(AppUtils.getAppContext(), sharedText , Toast.LENGTH_SHORT).show();
    }
}

void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
        // Update UI to reflect image being shared
        Toast.makeText(AppUtils.getAppContext(), imageUri.toString() , Toast.LENGTH_SHORT).show();
    }
}

void handleSendMultipleImages(Intent intent) {
    ArrayList imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    if (imageUris != null) {
        // Update UI to reflect multiple images being shared
    }

}

References:

No comments:

Post a Comment