Friday, 17 October 2014

Intent chooser - custom action button - example

Without saying empty words...
First we need make own Activity which will handle our action - in my example it will be a plain text which will be stored into android clipboard.

First our clipboard activity:

 public class ClipActivity extends Activity {  
   
   public static final String TAG = ClipActivity.class.getSimpleName();  
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
   
     if (getIntent().getExtras() != null) {  
       //just listing keys and values  
       for (String s : getIntent().getExtras().keySet()) {  
         Log.d(TAG, s + " " + getIntent().getExtras().getString(s));  
       }  
   
       //copying our text to android clipboard  
       if (getIntent().hasExtra("android.intent.extra.TEXT")) {  
         ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);  
         ClipData cd = ClipData.newPlainText("clipboard", getIntent().getExtras().getString("android.intent.extra.TEXT"));  
         cm.setPrimaryClip(cd);  
       }  
     }  
     Toast.makeText(this, "Copied by our app :)", Toast.LENGTH_SHORT).show();  
     finish();  
   }  
   
 }  

The second step is to declare our action intent in our manifest file.

 <activity android:name=".ClipActivity" android:noHistory="true" >  
      <intent-filter android:icon="@android:drawable/ic_dialog_alert" android:label="My label">  
           <action android:name="android.intent.action.SEND"/>  
           <category android:name="android.intent.category.DEFAULT"/>  
           <data android:mimeType="text/plain"/>  
      </intent-filter>  
 </activity>  

However it is possible your action will blink while action -> open activity-copy to clipboard-kill activity.

So you should use transculent theme like that:

     <activity android:name=".ClipActivity" android:noHistory="true" android:theme="@android:style/Theme.Translucent">  
       <intent-filter android:icon="@android:drawable/ic_dialog_alert" android:label="My label">  
         <action android:name="android.intent.action.SEND"/>  
         <category android:name="android.intent.category.DEFAULT"/>  
         <data android:mimeType="text/plain"/>  
       </intent-filter>  
     </activity>  

Now it's the matter of call our intent chooser :)

 Intent intent = new Intent();  
 intent.setAction(Intent.ACTION_SEND);  
 intent.putExtra(Intent.EXTRA_TEXT, "This is my text to copy.");  
 intent.setType("text/plain");  
   
 Intent chooser = Intent.createChooser(intent, "My Intent Chooser");  
   
 if(intent.resolveActivity(getActivity().getPackageManager()) !=null)  
      getActivity().startActivity(chooser);  

So as you see, it's nothing hard as it could be.