android - BroadcastReceiver 和 intent-filter?

标签 android android-intent broadcastreceiver

她就是我想要完成的:

  1. 当用户尝试从任何应用分享一些文本(如分享推文或链接)时,我的应用将出现在分享列表中。
  2. 如果他选择我的应用程序,将运行一些简单的代码(如显示 Toast),然后就可以了。不需要界面或用户界面。

这是我的做法:

AndroidManifest.xml

<receiver 
android:name=".MyBroadcastReceiver" >
    <intent-filter
        android:label="select my app">
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>                
</receiver>

MyBroadcastReceiver.java

public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    //Some simple code
    Toast.makeText(arg0, "My Receiver is cool", Toast.LENGTH_LONG).show();
}

这没有用,我的应用没有显示在共享列表中。

为什么我使用 BroadcatReceivers 而不是 Activities 因为我不想要任何 UI,我认为这就是为什么我们有接收器(请纠正我的错误)

我做的对吗?

最佳答案

This didn't work, my app doesn't show in the sharing list.

ACTION_SEND 用于 Activity 。您正在尝试使用 BroadcastReceiver。由于 BroadcastReceiver 不是 Activity ,因此这将不起作用。

Am I doing it right?

没有。

If he select my app, some simple code will be run (like showing a Toast) then that's it. No interface or UI is needed.

您仍然需要 Activity 。但是,如果您为 Activity 提供 Theme.NoDisplay,并且您不调用 setContentView(),则 Activity 将没有 UI。通常,您只需在完成您想做的任何事情后从 onCreate() 调用 finish()(在本例中,显示一个 Toast ).

例如,this sample application显示一个 Activity (FauxSender) 设置为精确执行您想要的操作:使用 Toast 响应 ACTION_SEND。它有另一个发出 ACTION_SEND 的 Activity ,因此您可以看到结果。

关于android - BroadcastReceiver 和 intent-filter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10439927/

相关文章:

android: widget: service::How to update widget and activity control's text/image 从服务

android - RecyclerView 滚动到顶部,AsyncListDiffer 不起作用

android - 使用BroadcastReceivers的一些问题

java - 在 Android >= Api 26 中不调用 BroadcastReceiver

android - 如何在Android上使用strace?

android - 如何在 Android 中以编程方式放大图像?

android - 如何停止在我的应用程序中拦截 Zxing Intent ?

java - 启动 Intent 应用程序崩溃

安卓 4.1+ : Change number before it is written to the call log?

java - 带有监听器的 BroadcastReceiver 在不使用时会耗尽电池