【问题标题】:broadcast receiver not received in IntentServiceIntentService 中未收到广播接收器
【发布时间】:2017-11-16 07:26:22
【问题描述】:

我正在构建一个能够从 FirebaseMessagingService 捕获意图的服务。

我使用的第一个版本在主要活动的应用程序级别执行此操作,但我不想再在此级别处理它。我创建了如下意图服务:

package com.seb.sebastien.appservices;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.util.Log;

public class appsControlIntentService extends IntentService {
    public static final String REQUEST_MSG = "request";
    public static final String RESPONSE_MSG = "response";
    public static final String TAG = "appsControlIntentService";
    private String type_sim;


    public appsControlIntentService() {
        super("appsControlIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        boolean request = intent.getBooleanExtra(REQUEST_MSG, false);

        if(request == true) {
            sendResponse("Enable");
            handleAction(getCarrier());
            registerAllReceivers();
        }
        else if (request == false) {
            sendResponse("Disable");
            unRegisterAllReceivers();
            disableAction();
        }
        else
            Log.e(TAG, "Error msg");

    }
    ...

    /* Firebase and SIM */
    private BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Broadcast received");
            if (intent.getExtras().getString(appFirebaseMessagingService.FIREBASE).equals(appFirebaseMessagingService.FIREBASE))
                type_sim = intent.getExtras().getString(appFirebaseMessagingService.SIM_TYPE);
            else if(intent.getExtras().getString(SimNotificationService.EXTRA_SIM_STATE) != null)
                Log.d(TAG, "Get something from Sim");
            else
                type_sim = null;

            if(type_sim != null){
                handleAction(type_sim);
            }
        }
    };

    private void registerAllReceivers(){
        Log.d(TAG, "Broadcast receiver register");
        registerReceiver(serviceBroadcastReceiver, new IntentFilter(appFirebaseMessagingService.INTENT_FILTER));
    }

    private void unRegisterAllReceivers() {
        if (serviceBroadcastReceiver != null) {
            unregisterReceiver(serviceBroadcastReceiver);
            serviceBroadcastReceiver = null;
        }
    }

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

}

此意图服务注册一个广播接收器,以便能够接收 firebase 广播,如下所示:

package com.seb.sebastien.appservices;

public class appFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "appFirebaseMessagingService";
    public static final String INTENT_FILTER = "INTENT_FILTER";
    public static final String FIREBASE = "firebase";
    public static final String SIM_TYPE = "simtype";

    public appFirebaseMessagingService() {
    }

   /* @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    } */

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String sim = null;

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            sim = remoteMessage.getNotification().getBody();
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        Intent intent = new Intent(INTENT_FILTER);
        intent.putExtra(FIREBASE, FIREBASE);
        intent.putExtra(SIM_TYPE, sim );

        sendBroadcast(intent);

    }
}

调试时,我看到我们一直到 sendBroadcast,但如果我注册了接收器,“appControlIntentService”类事件中似乎没有收到任何内容。

知道为什么在意图服务中没有收到广播吗?

【问题讨论】:

    标签: android firebase intentservice android-broadcastreceiver android-intentservice


    【解决方案1】:

    首先,不确定您实际在哪里创建了 appsControlIntentService 的实例。

    其次,当onHandleIntent 完成时,IntentService 会停止。它旨在完成一项简短的任务并完成。所以基本上即使你创建了一个来收听广播,它也只会在非常有限的时间内这样做,直到它的 onDestroy 被调用。

    关于用于监听您的自定义意图的 BroadcastReceiver 解决方案:

    1) 创建一个在后台运行的服务(不是 IntentService,常规服务),并让它注册一个 BroadcastListener。您可以在您的活动第一次唤醒时创建此服务,并且可能在 Boot BroadcastReceiver 中。确定您希望它是前台服务还是后台服务。由于内存问题,后台服务更有可能被操作系统杀死。但前台服务要求您在状态栏中显示一个图标。

    2) 只需将 BroadcastReceiver 放入清单中。这样,操作系统甚至会在广播到达时唤醒应用程序来处理广播。即使应用程序当前未运行。 在https://developer.android.com/guide/components/broadcasts.html 中查看“清单声明的接收者”。

    要禁用此接收器,请查看:Android - how to unregister a receiver created in the manifest?。或者,您可以保存在共享首选项中,无论您是否希望它对事件执行某些操作,或者更好的是,如果 FirebaseMessagingService 首先被禁用,则不要从它发送意图。

    【讨论】:

    • 谢谢,但在这种情况下,我怎么能在后台运行一些东西来监听广播?我在想使用意图服务你认为服务会更好吗? ?目标是根据 Firebase 消息禁用一些应用程序。例如,一旦服务接收到一个应用程序,该服务将禁用一个包含“禁用”的正文。
    【解决方案2】:

    你应该像这样对广播接收器使用警报管理器 -

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
            Intent alarmIntent = new Intent(MainActivity.this, BroadCastReciever.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
                    alarmIntent, 0);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                        + duration(in millisecond), pendingIntent);
            } else {
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                        + in millisecond, pendingIntent);
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多