没有GUI的Android Activity

Isa*_*ler 29 user-interface android intentfilter broadcastreceiver android-service

我创建了一个仅用于从链接启动的活动(使用intent过滤器.)我不希望这个活动有一个GUI - 我只是想让它启动一个服务并在栏中发出通知.我试图在我的服务中为链接设置intent过滤器,但这不起作用.有没有更好的方法来回答意图过滤器 - 或者我可以让我的活动没有GUI吗?
对不起,如果我困惑,艾萨克

Joe*_*eHz 96

与先前的响应相呼应,您不应使用广播接收器.

在同样的情况下,我所做的就是如此宣布主题:

<activity android:name="MyActivity"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.NoDisplay">
Run Code Online (Sandbox Code Playgroud)

  • 唉,我发布后很好地回答了这个问题,这可能解释了为什么没有发生这种情况.给我一个死灵法师徽章,以及你的评论让我微笑:) (5认同)
  • 这个答案应该有更多的赞成,因为它回答了所提出的确切问题.其他答案是非常正确的,但这实际上非常有用,并回答了被问到的问题. (3认同)

Ret*_*ier 19

你最好的选择似乎是使用BroadcastReceiver.您可以创建一个新的BroadcastReceiver来侦听Intent以触发您的通知并启动您的服务,如下所示:

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));
    }
  }    
}
Run Code Online (Sandbox Code Playgroud)

您可以直接在应用程序清单中注册此IntentReceiver,而无需将其包含在活动中:

<?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> 
Run Code Online (Sandbox Code Playgroud)