How to create BroadcastReceiver without Activity

做~自己de王妃 提交于 2019-12-04 08:25:55

What you are trying to do is wrong for at least the following reasons...

  1. MAIN/LAUNCHER only apply to activities and as you don't have a class which extends Activity in your code, this is what is causing the error.
  2. Although there's nothing wrong with an 'app' which implements just a BroadcastReceiver or Service, it is good practice to let the user know that things have been initialized correctly. Even if you could list a receiver/service in 'All apps', if they select it and see nothing happens they're not going to be happy - users like to see some feedback.

In short, create a simple Activity which will appear in 'All apps' and has the MAIN/LAUNCHER intent settings and when it starts just have it create a dialog saying something like "Hi, welcome to ..." or some other feedback to the user letting them know that things have started correctly. Have an 'OK' button on the dialog which when pressed, calls the Activity's finish() method leaving the receiver in place.

One way to hide the Activity is by using the following theme in the Android Manifest File of your application:

<activity
    android:name=".SomeActivity"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

NOTE: Using this does make your app not show up when launched, but it still does not get rid of the launcher icon. And if you remove the icon you wouldn't be able to launch the app. (Figure your way around that one!)

from sendBroadcast() documentation:

No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(Intent, String).

use sendOrderedBroadCast() instead

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