在服务内部使用广播接收者

问题描述 投票:0回答:1

我正在尝试在Service类中使用Broadcast Receiver。但是不会调用Broadcast Receiver中的onReceive方法。我不知道问题出在哪里。下面是我的代码,


public class CallService extends Service {
    CallReceiver callReceiver=null;
    String TAG=CallService.class.getSimpleName();

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        CallReceiver callReceiver=new CallReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        intentFilter.addAction("a");
        this.registerReceiver(callReceiver,intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: started in call service");
        CallReceiver callReceiver=new CallReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        intentFilter.addAction("a");
        this.registerReceiver(callReceiver,intentFilter);

    }

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





    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public class CallReceiver extends BroadcastReceiver{


        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equalsIgnoreCase("a"))
                Log.d("CallService", "onReceive: aa");
        }
    }
}

我已在onCreate和onStart中将动作添加到意图过滤器中。注册后,它将转到onReceive方法,并需要检查Action。我对吗?但是在我的情况下,不会调用onReceive方法。任何人都可以帮助我找到更好的解决方案。

android android-studio service broadcastreceiver
1个回答
0
投票

我不能在服务中使用接收器,因为它通常会使用接收器来调用服务,如果您想要稳定的服务来进行更新,则可以使用意图服务。但是,如果您使用接收器进行系统更新(如wifi关闭/打开等),则可以创建接收器并从清单中进行注册,这样它就始终可以工作,您可以从接收器中调用服务,也可以在接收方法中编写代码]

© www.soinside.com 2019 - 2024. All rights reserved.