java - 包含 BroadCastReceiver 的服务无法正常运行

标签 java android broadcastreceiver intentservice

Please see edits before answering!

我有一个包含BackgroundService类的应用程序:

public class BackgroundService extends Service {

@Override
public void onCreate() {
    super.onCreate();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.spotify.music.playbackstatechanged");
    filter.addAction("com.spotify.music.metadatachanged");
    filter.addAction("com.spotify.music.queuechanged");

    registerReceiver(receiver, filter);

    Log.e("Playing:", "APP IS PLAYING");

    Notification notification = new Notification();
    startForeground(1, notification); 

}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        long timeSentInMs = intent.getLongExtra("timeSent", 0L);

        String action = intent.getAction();

        if (action.equals(BroadcastTypes.METADATA_CHANGED)) {

            String trackId = intent.getStringExtra("id");
            String artistName = intent.getStringExtra("artist");
            String albumName = intent.getStringExtra("album");
            String trackName = intent.getStringExtra("track");
            int trackLengthInSec = intent.getIntExtra("length", 0);


            // Do something with extracted information...

        } else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {

            boolean playing = intent.getBooleanExtra("playing", false);

            Log.e("Playing:","TRUE");

        }
    }
};

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


static final class BroadcastTypes {
    static final String SPOTIFY_PACKAGE = "com.spotify.music";
    static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
    static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
}


}

这是在我的 list 中声明的​​:

<service
        android:name=".BackgroundService"
        android:enabled="true" >
        <intent-filter>
            <action android:name="com.spotify.music.playbackstatechanged" />
            <action android:name="com.spotify.music.metadatachanged" />
            <action android:name="com.spotify.music.queuechanged" />
        </intent-filter>
    </service>

所以本质上我的目标是在我的应用程序打开时初始化我的BackgroundService,并让它继续在后台运行,做我需要它做的任何事情。截至目前,我正在使用日志来确定我的“设置”是否正常工作,但是当我运行我的应用程序时,即使在测试了应触发我的 BroadCastReceiver 的所有操作后,我也无法看到日志。此外,如果我的服务正在运行,我的持久通知应该已经改变,但它没有......

Edit::

因此,我将日志添加到了BackgroundService 的onCreate() 和onReceive() 方法中,但是,这两个方法似乎都没有出现。我想知道,我是否需要在启动器 Activity 中执行某些操作来初始化服务?此外,没有显示任何通知,因此我假设该服务由于某种原因没有启动......

Latest Edit:

因此,我将以下代码添加到我的主要 Activity 中,看看它是否会产生影响:

        startService(new Intent(this,BackgroundService.class));

调试我的应用程序后,我开始看到以下错误:

    java.lang.RuntimeException: Unable to create service com.aurum.mutify.BackgroundService: java.lang.SecurityException: Isolated process not allowed to call registerReceiver

指向我的广播接收器类。

最佳答案

Intent 服务专为短期任务而设计。并且你的 Intent 处理方法是空的。

如果您需要在后台长时间运行任务,请使用标准服务并调用启动前台。这将最大限度地减少系统破坏您的服务的机会。

要了解更多信息,请访问 here

编辑

尝试重写 onStartCommand 方法。这个方法在服务启动时被调用,通常你在这里做所有的事情。请记住,有 3 个返回选项。

编辑2: 尝试这样的事情 在创建时

PendingIntent pi;
BroadcastReceiver br;
Intent myIntent;

 @Override
  public void onCreate()
  {
    super.onCreate();

     myIntent = new Intent("something")


   if(Build.Version.SDK_INT >= 16)     //The flag we used here was only added at API 16    
    myIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    //use myIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if you want to add more than one flag to this intent;

    pi = PendingIntent.getBroadcast(context, 1, myIntent, 0); 

    br = new BroadcastReceiver ()
    {
      public void onReceive (Context context, Intent i) {
        new thread(new Runnable()
        {
          public void run()
          {
            //do something
          }
        }).start();
      }
    };

然后在启动命令中

 this.registerReceiver(br, new IntentFilter("something"));

关于java - 包含 BroadCastReceiver 的服务无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060962/

相关文章:

android - 应用未运行时 BroadcastReceiver 不工作

java - 从大量 Swing 文本字段收集数据

java - 在 Java 中对字符串进行标记

android - BottomNavigationView - 阴影和波纹效果

java - 如何让 android 复选框禁用布局中的某些内容?

android - 如何在 Android 中播放任意时间的视频?

android - 应用内广播接收器

java - 用 JAVA 固定十进制数

java - 如何检查 Eclipse 插件性能

java - 等待 onReceive 运行并停止