将广播发送到不在前台的活动

时间:2016-02-16 14:42:27

标签: android android-broadcastreceiver

我有一个具有CountdownTimer的后台服务。当CountdownTimer倒计时我向广告发送广播。当CountdownTimer倒计时时,会提示活动,我可以停止服务并取消注册接收器。

我已将正常的接收方取消注册方法从onStop和onPause移动到我自己的方法中,一旦收到广播,我就会调用" timer_finished"。这样我就可以在不取消注册的情况下离开活动。

如果用户当前正在查看活动,则一切正常。如果用户离开活动,CoundownTimer仍在运行,但活动没有接收广播。

我该怎么做才能让活动收到最后的广播" timer_finished"?

public class CountDownBroadcastService extends Service {

    private static final String TAG = CountDownBroadcastService.class.getSimpleName();

    public static final String COUNTDOWN_BR = "com.carefreegroup.rr3.countdown_br";
    Intent bi = new Intent(COUNTDOWN_BR);

    CountDownTimer cdt = null;
    Context mContext;

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

            mContext = this;

            Log.i(TAG, "Starting timer...");


            cdt = new CountDownTimer(10000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
                    bi.putExtra("countdown", millisUntilFinished);
                    bi.putExtra("timer_status", "timer_not_finished");
                    sendBroadcast(bi);
                }

                @Override
                public void onFinish() {
                    Log.i(TAG, "Timer finished");

                    bi.putExtra("timer_status", "timer_finished");


                    sendBroadcast(bi);

                }
            };

            cdt.start();
        }

        @Override
        public void onDestroy() {

            cdt.cancel();
            Log.i(TAG, "Timer cancelled");
            super.onDestroy();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {       
            return super.onStartCommand(intent, flags, startId);
        }

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

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "start of oncreate");

        setContentView(R.layout.loneworker);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.ic_launcher);
        setTitle("Lone Worker");
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        tvCountDown = (TextView)findViewById(R.id.tvloneworkercountdown);
        callFinished = (Button)findViewById(R.id.buttonlwcallfinished);


        callFinished.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Log.e(TAG, "inside callFinished");
                //maybe alert carer is safe***************************************

                setCountDownFinished();

            }
        });




        startService(new Intent(this, CountDownBroadcastService.class));
        Log.i(TAG, "Started service");






    }//end of onCreate



    private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {            
            updateGUI(intent); // or whatever method used to update your GUI fields
        }
    };


    public void onResume() {
        super.onResume();        
        registerReceiver(br, new IntentFilter(CountDownBroadcastService.COUNTDOWN_BR));
        Log.i(TAG, "Registered broacast receiver");
        }



    private void updateGUI(Intent intent) {
        if (intent.getExtras() != null) {
            long millisUntilFinished = intent.getLongExtra("countdown", 0);
            //Log.i(TAG, "Countdown seconds remaining: " +  millisUntilFinished / 1000);    

            String status = intent.getStringExtra("timer_status");

            if(status.equalsIgnoreCase("timer_not_finished")){

                    tvCountDown.setText("Countdown seconds remaining: " +  millisUntilFinished / 1000);

            }else if(status.equalsIgnoreCase("timer_finished")){

                setCountDownFinished();
            }
        }
    }//end of updateGUI


    public void setCountDownFinished(){

        tvCountDown.setText("0");
        unregisterReceiver(br);
        Log.i(TAG, "Unregistered broacast receiver");

        stopService(new Intent(this, CountDownBroadcastService.class));
        Log.e(TAG, "Stopped CountDownBroadcastService");

    }// end of setCountDownFinished()




}

1 个答案:

答案 0 :(得分:1)

  

以编程方式注册广播接收器时   活动时,活动暂停时不会播放广播。该   BroadcastReceiver文档并不像它们那样清晰   点。他们建议仅在onPause上取消注册以减少系统   高架。        如果您希望即使活动不在前台也能接收事件,请使用以下命令在清单中注册接收器   接收器元素。