How to fire an event like launch an application wh

2020-05-21 06:33发布

问题:

I was wondering if i can launch an activity or application when a text is selected in any application like browser, messages etc.

Like when we select a text at any where a small pop-up appears mentioning cut, copy, paste option. can i add another button there? to launch my application?

if i can please guide me how can i do that and send data to my application..

Thank you !

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.main);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

回答1:

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



回答2:

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