应用程序终止后,服务中的CountDownTimer停止了 - Android

时间:2015-11-25 08:02:47

标签: android android-service countdowntimer android-broadcastreceiver

我是服务和BroadcastReceiver的新手,所以也许这个问题是新手,但是我在网上长时间搜索后没有找到解决方案。

我需要在服务中运行CountDownTimer,所以即使应用程序完成也要继续运行。

在我的代码中,我基于THIS EXAMPLE.

我的代码工作正常,但在应用程序完成后,CountDownTimer停止了(服务没有被破坏,只是计时器)。

我尝试以不同的方式实现它,但没有任何方法可以帮助我。

这是我的相关代码的一部分:

AlarmReciver

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent background = new Intent(context, BackgroundService.class);
        Bundle bundle =  intent.getExtras();

        background.putExtra("time", bundle.getInt("time"));
        context.startService(background);
    }
}

后台服务

public class BackgroundService extends Service {

    private final static String TAG = "BroadcastService";

    private CountDownTimer cdt = null;
    private Bundle bundle;
    private boolean isRunning;
    private Context context;
    private int timeInMili;

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
         this.context = this;
         this.isRunning = false;

    }


    @Override
    public void onDestroy() { 
        //cdt.cancel();
        Log.i(TAG, "Timer cancelled");
        super.onDestroy();
    }

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

        bundle =  intent.getExtras();
        timeInMili = bundle.getInt("time");

         if(!this.isRunning) {
             this.isRunning = true;
         }

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

                 Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);

             }

             @Override
             public void onFinish() {

                 Log.i(TAG, "Timer finished");
                 stopSelf();
             }
         };
         cdt.start();
        return START_STICKY;
    }
}

MainActivity (扩展FragmentActivity):

public void StartBackgroundAlarm(int timeInMili)
    {

         Intent alarm = new Intent(this, AlarmReceiver.class);
         alarm.putExtra("time", timeInMili);
         PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
         AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
         alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pendingIntent);

    }

MANIFEST

 <service android:enabled="true" android:name= "com.MES.yo.servicemanager.BackgroundService" />
 <receiver android:name="com.MES.yo.servicemanager.AlarmReceiver"></receiver>

0 个答案:

没有答案