Android服务运行计时器即使用户离开应用程序(销毁它)

时间:2016-08-24 12:13:37

标签: android service countdowntimer

我创建了一个应用程序,用户按下按钮然后我用CountDownTimer启动服务。当计时器停止时,我创建通知。当应用程序运行时,一切都很完美,但是当用户关闭应用程序时,我不会收到任何通知。我通过移除unregisterReceiveronPause上的onStop来解决此问题。但是,当用户销毁应用程序(完全从后台删除应用程序)时,我根本不会收到任何通知。即使应用程序被销毁,如何继续服务? 这是我的服务

public class TimerService extends Service {
    private final static String TAG = "BroadcastService";

    public static final String COUNTDOWN_BR = "your_package_name.countdown_br";
    private Intent intent = new Intent(COUNTDOWN_BR);

    private CountDownTimer countDownTimer;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        long time = intent.getLongExtra("time", 0);
        Log.d("SDKJDSDSDSDSDSDSD", time + "");
        startCount(time);
        return super.onStartCommand(intent, flags, startId);
    }

    private void startCount(long time){
        Log.d("SDIUSDSDSD", time + "");
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                intent.putExtra("countdown", millisUntilFinished);
                sendBroadcast(intent);
            }

            @Override
            public void onFinish() {
                intent.putExtra("countdown", -1);
                sendBroadcast(intent);
            }
        };

        countDownTimer.start();
    }

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

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

这是我如何开始服务的 我的StartTimerActivirt类

public class DetailChargeActivity extends AppCompatActivity implements  View.OnClickListener{
    private Button startCharge, startReserveButton;
    private int selectedYear = -1, selectedMonth = -1, selectedDay = -1;
    private int startH = -1, startMin = -1, endH = -1, endMin = -1;
    private Chronometer chronometer;
    private boolean chronometerStarted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_charge);

        //.... set up listeners and so on...
    }

    @Override
    public boolean onSupportNavigateUp() {
        super.onSupportNavigateUp();
        finish();
        return true;
    }

    @Override
    public void onClick(View view) {
        startTimer(0, 2);
    }


    private void startTimer(int startH, int startMin){
        long time = TimeUnit.MINUTES.toMillis(startH * 60 + startMin);
        Intent intent = new Intent(this, TimerService.class);
        intent.putExtra("time", time);
        startService(intent);
    }

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

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(br, new IntentFilter(TimerService.COUNTDOWN_BR));
    }

    @Override
    public void onPause() {
        super.onPause();
       // unregisterReceiver(br);
    }

    @Override
    public void onStop() {
        try {
          //  unregisterReceiver(br);
        } catch (Exception e) {
            // Receiver was probably already stopped in onPause()
        }
        super.onStop();
    }
    @Override
    public void onDestroy() {
        stopService(new Intent(this, TimerService.class));
        super.onDestroy();
    }

    private void updateGUI(Intent intent) {
        if (intent.getExtras() != null) {
            long millisUntilFinished = intent.getLongExtra("countdown", 0);
            Log.d("DSDafsdfdfKSD", "SASASASSASAS " + (millisUntilFinished / 1000));
            if(millisUntilFinished == 0) {
                buildNotification();
            }
        }
    }

    private void buildNotification(){
        Log.d("DSDafsdfdfKSD", "ASASSA");
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_cast_dark)
                        .setContentTitle("My notification")
                        .setContentText("Hello World!");

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, mBuilder.build());
    }
}

1 个答案:

答案 0 :(得分:0)

return START_STICKY;中返回onStartCommand(),以便在用户销毁时尽快启动服务。

通过检测,将剩余时间保存在每onTick public class TimerService extends Service { private final static String TAG = "BroadcastService"; public static final String COUNTDOWN_BR = "your_package_name.countdown_br"; private Intent intent = new Intent(COUNTDOWN_BR); SharedPreferences mPrefs; private CountDownTimer countDownTimer; // here is prefs key String Key = "TIME"; @Override public int onStartCommand(Intent intent, int flags, int startId) { long time = 0; mPrefs = this.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE); if (mPrefs.getLong(Key, 0) == 0) { time = intent.getLongExtra("time", 0); mPrefs.edit().putLong(Key, time).apply(); } else { time = intent.getLongExtra("time", 0); } // now start the counter Log.d("SDKJDSDSDSDSDSDSD", time + ""); startCount(time); return START_STICKY; } private void startCount(long time) { Log.d("SDIUSDSDSD", time + ""); countDownTimer = new CountDownTimer(time, 1000) { @Override public void onTick(long millisUntilFinished) { long remainingTime = mPrefs.getLong(Key, 0) - millisUntilFinished; mPrefs.edit().putLong(Key, remainingTime).apply(); intent.putExtra("countdown", millisUntilFinished); sendBroadcast(intent); } @Override public void onFinish() { intent.putExtra("countdown", -1); sendBroadcast(intent); } }; countDownTimer.start(); } @Override public void onDestroy() { countDownTimer.cancel(); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } 。阅读评论

无论如何,服务将以剩余时间重新启动。

dtInstance