0

我正在尝试从 JobService 发送广播并从活动中接收它。

这是我尝试过的

我的工作服务

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters params) {
       if (!HomeActivity.isOpen) {
          Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
       } else {
          Intent sendNoti = new Intent("location_turned_off");
          sendBroadcast(sendNoti);
       }
       jobFinished(params, false);
       return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }
}

在我的活动中

public static boolean isOpen;
@Override
protected void onResume() {
   super.onResume();
   isOpen = true;
   LocalBroadcastManager.getInstance(this).registerReceiver(locationTurnedOff,new IntentFilter("location_turned_off"));
}
    @Override
    protected void onPause() {
      super.onPause();
      isOpen = false;          
   LocalBroadcastManager.getInstance(this).unregisterReceiver(locationTurnedOff);                                                      
    }



private BroadcastReceiver locationTurnedOff = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("onReceive","Broadcast received");//nothing is triggered here
    }
};

编辑

我有条件地发送广播,如果活动处于 onResume 状态,我正在发送广播

4

0 回答 0