如何将广播接收器 运行 保持在后台?

How to keep broadcast receiver running in background?

我有一个广播接收器。但它会在 activity 关闭时销毁....我如何将它 运行 保留在后台。我知道我可以通过使用服务来做到这一点......但是我如何在服务中实现它?


开始时:

 @Override
    protected void onStart() {
        super.onStart();
        
        private final BroadcastReceiver broadcast = new Broadcast();
        IntentFilter filter = new IntentFilter("Update Player");
        registerReceiver(broadcast, filter);
        isReceiverRegistered = true;
    }

广播:

///BroadcastReceiver
    public class Broadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, final Intent intent) {

            String action = intent.getAction();

            if (action.equalsIgnoreCase("Update Player")) {
                position = intent.getIntExtra("position_2", -1);
                setTextView();
                byte[] image = getArt(PlayingScreen_List.get(position).getPath());
                if (image != null) {
                    Glide.with(getApplicationContext()).asBitmap()
                            .load(image)
                            .into(profile_image);
                } else {
                    Glide.with(getApplicationContext()).asBitmap()
                            .load(R.drawable.allsongs)
                            .into(profile_image);
                }
            }
         }
    }

暂停:

@Override
protected void onPause() {
    super.onPause();

    if (isReceiverRegistered) {
        unregisterReceiver(broadcast);
        isReceiverRegistered = false;
    }
}

您需要创建延伸至 Service 的 class。添加内部 class 到它延伸到 BroadcastReceiver。查看此代码。

public class MyService extends Service {
    BroadcastReceiver broadcastReceiver;

    public class MyReceiver extends BroadcastReceiver {    
        @Override
        public void onReceive(Context context, Intent intent) {
            // do something
        }

        // constructor
        public MyReceiver(){    
        }
    }

    @Override
    public void onCreate() {
         // create IntentFilter
         IntentFilter intentFilter = new IntentFilter();

         //add actions 
         intentFilter .addAction("com.example.NEW_INTENT");
         intentFilter .addAction("com.example.CUSTOM_INTENT");
         intentFilter .addAction("com.example.FINAL_INTENT");

         //create and register receiver
         broadcastReceiver = new MyReceiver();
         registerReceiver(broadcastReceiver, intentFilter );
    }
}

在您的清单中添加此代码:

<receiver android:name="MyReceiver">
     <intent-filter>
        <action android:name="com.example.NEW_INTENT">
        </action>
        <action android:name="com.example.CUSTOM_INTENT">
        </action>
        <action android:name="com.example.FINAL_INTENT">
        </action>
     </intent-filter>
</receiver>