0

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

我需要在服务内部运行一个 CountDownTimer,所以即使应用程序完成,时间也会继续移动。

在我的代码中,我基于这个示例。

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

我试图以不同的方式实现它,但对我没有任何作用。

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

报警接收器

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);

    }

清单

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

0 回答 0