Android Activity with no GUI

空扰寡人 提交于 2019-11-27 18:22:09
Reto Meier

Your best bet would seem to be using a BroadcastReceiver. You can create a new BroadcastReceiver that listens for the Intent to trigger your notification and start your service like this:

public class MyIntentReceiver extends BroadcastReceiver {    
  @Override 
  public void onReceive(Context _context, Intent _intent) {
    if (_intent.getAction().equals(MY_INTENT)) {
      // TODO Broadcast a notification
      _context.startService(new Intent(_context, MyService.class));
    }
  }    
}

And you can register this IntentReceiver directly in the application Manifest without needing to include it within an Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.domain.myapplication">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <service android:enabled="true" android:name="MyService"></service>
    <receiver android:enabled="true" android:name="MyIntentReceiver">
      <intent-filter>
        <action android:name="MY_INTENT" />
      </intent-filter>
    </receiver>
  </application>
</manifest> 
JoeHz

Echoing previous response, you shouldn't use a broadcast receiver.

In the same situation, what I did was to declare the theme thusly:

<activity android:name="MyActivity"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.NoDisplay">

I'm not sure if a service would work, but a broadcast receiver definitely would not. Url's are launched using startActivity(). Broadcast receivers cannot respond to this.

http://developer.android.com/reference/android/content/BroadcastReceiver.html

FTA: Note that, although the Intent class is used for sending and receiving these broadcasts, the Intent broadcast mechanism here is completely separate from Intents that are used to start Activities with Context.startActivity(). There is no way for a BroadcastReceiver to see or capture Intents used with startActivity(); likewise, when you broadcast an Intent, you will never find or start an Activity.

Use Service. I works definitely. When you click the program, it would do its work without any GUI. Use pendintgintent...getService(MySerice.class....). Then, create a new class MyService extending the Service class. Inside MyService.class, override onStart() and do whatever you want to do.

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