How to fire an event like launch an application when a text is selected

拈花ヽ惹草 提交于 2019-12-02 21:14:58

The closest thing to what you're describing would be for your app to register as handling the android.intent.action.SEND intent, as described here:

http://developer.android.com/training/sharing/receive.html

The intent-filter declaration would look something like this:

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

What the user sees...

When a user is in some other app and selects text, if it's supported by the app they'll get the copy & paste options you've already seen, but they'll also get the 'share' option - the icon is three dots connected by two lines:

...and when the user then taps on the 'Share' icon:

Your app will appear in the list of apps that are displayed to the user. If the user selects your app, you'll receive an intent with the shared text which you can then extract, ie:

String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);

Further reading

http://android-developers.blogspot.com/2012/02/share-with-intents.html

Android 6.0 Marshmallow introduced ACTION_PROCESS_TEXT. It allows you to add custom actions to that text selection toolbar.

First, you have to add an intent filter in your Manifest,

<activity android:name=".YourActivity" 
          android:label="@string/action_name">
  <intent-filter>
    <action android:name="android.intent.action.PROCESS_TEXT"/>
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
  </intent-filter>
</activity>

then in YourActivity that you want to launch when user selects a text.

Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.process_text_main);
  CharSequence text = getIntent()
      .getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT);
  // process the text
}

Source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!