如何在选择文本时触发启动应用程序等事件

时间:2013-04-29 14:41:33

标签: android android-intent android-broadcast

我想知道在浏览器,消息等任何应用程序中选择文本时是否可以启动活动或应用程序。

就像我们在任何小弹出窗口中选择剪切,复制,粘贴选项的文本一样。我能在那里添加另一个按钮吗?启动我的申请?

如果我可以请指导我该怎么做并将数据发送到我的应用程序..

谢谢!

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);

2 个答案:

答案 0 :(得分:5)

与您描述的内容最接近的是您的应用注册为处理android.intent.action.SEND意图,如下所述:

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

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>

用户看到的内容......

当用户在某个其他应用中并选择文字时,如果应用支持该应用,则他们会获得副本&amp;您已经看过的粘贴选项,但它们也会获得'分享'选项 - 图标是由两行连接的三个点:

enter image description here

...然后当用户点击“分享”图标时:

您的应用将显示在向用户显示的应用列表中。如果用户选择了您的应用,您将收到一个包含共享文本的意图,然后您可以提取该意图,即:

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

进一步阅读

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

答案 1 :(得分:3)

Android 6.0 Marshmallow介绍了ACTION_PROCESS_TEXT。它允许您向该文本选择工具栏添加自定义操作。

首先,您必须在Manifest中添加一个intent过滤器,

<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>

然后在用户选择文字时要启动的YourActivity

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