How to share data in Android
The Android API provides the share action which can be integrated as a menu item. This tutorial demonstrates the same.
Main Layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /></RelativeLayout> |
Menu xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_share" android:orderInCategory="100" android:showAsAction="ifRoom" android:actionProviderClass="android.widget.ShareActionProvider"/></menu> |
Java Code
Let’s now see the java code for this:
MainActivity.java
package com.example.shareactionexample;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.ShareActionProvider;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share); ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider(); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, "text to share"); mShare.setShareIntent(shareIntent); return true; }} |
Screenshots for android share menu item
1) The popup for sharing anything is shown below:
2) The data has been shared in the messaging app:


0 comments: