【问题标题】:Running method after every 5 minutes in service above sdk 21sdk 21以上服务每5分钟后的运行方法
【发布时间】:2017-02-02 12:41:15
【问题描述】:

正如我所读到的,无论您在警报管理器中定义什么时间段,它都会在 sdk 21 之上每 1 分钟触发一次。我正在运行一项服务,我希望我的方法在每 5 分钟后执行一次。这是我做的代码

public class Servicebackground extends Service {
@Nullable
@Override

public IBinder onBind(Intent intent) {
    System.out.println("service started in onBind");
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Intent notificationIntent = newIntent(this,MyLocationListener.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);


    System.out.println("service started in on create");




    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("service stopped");

}


@Override
public void onCreate() {


        return;
    }


    public class MyLocationListener extends BroadcastReceiver implements LocationListener {

    @Override
    public void onReceive(Context context, Intent intent) {


        Intent  ii = new Intent(context, Servicebackground.class);
        startService(ii);
        }

在课堂上我正在调用我已经完成的服务

    startService(new Intent(this, Servicebackground.class));

但即使我已将时间定义为 5 分钟,该方法也会在每分钟之后运行一次。我读到,在 sdk 21 之后,无论您定义什么时间,如果您使用警报管理器,该方法将在每 1 分钟后执行一次。

如果有任何错误,请告诉我。或者请建议我任何其他方式,即使应用程序被杀死并且该方法每 5 分钟执行一次,我也可以在后台运行服务。如果有其他可能的方式,请建议。

【问题讨论】:

    标签: java android service alarmmanager handler


    【解决方案1】:

    使用处理程序和定时器任务

    Timer timer;
    TimerTask task;
    private Handler handler;
    @Override
    protected void onCreate() {
        handler = new Handler();
        if (Build.VERSION.SDK_INT > 21) {
         startTimerTask();
       }
    }
    
    public void startTimerTask() {
    
        Log.w("--> ", "Start timer call");
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       executeMethod();
                    }
                });
            }
        };
        timer.schedule(task, 0, 60000 * 5);
    }
    
     private void executeMethod() {
       //   Do what you want
    }
    

    【讨论】:

    • 即使应用程序将被杀死,定时器任务是否会触发该功能。?
    • 是的,如果有写入服务,那么它肯定会触发.... @VipinNU
    【解决方案2】:

    alaram setReating 无法使用 api 19,因此您使用处理程序手动重复过程。参考AlarmManager fires alarms at wrong time

    Handler handler;
        Timer timer;
        TimerTask doAsynchronousTask;
        public AlarmManager alarm;
    

    onResume

    Intent intent = new Intent(getActivity(),Services.class);
    
    final Calendar cal = Calendar.getInstance();
            pintent = PendingIntent.getService(getActivity(), 0, intent, 0);
            alarm = (AlarmManager) getActivity().getSystemService(
                    Context.ALARM_SERVICE);
    
    
                if (Const.DEVICE_API_INT < Const.ANROID_API_LOILLIPOP) {
                    alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                            cal.getTimeInMillis(), 3 * 1000, pintent);
                } else {
    
                    handler = new Handler();
                    timer = new Timer();
                    doAsynchronousTask = new TimerTask() {
    
                        @Override
                        public void run() {
                            handler.post(new Runnable() {
    
                                @SuppressLint("NewApi")
                                public void run() {
                                    try {
                                        alarm.setExact(AlarmManager.RTC_WAKEUP,
                                                cal.getTimeInMillis(), pintent);
    
                                    } catch (Exception e) { // TODO Auto-generated
                                                            // catch
                                    }
                                }
                            });
                        }
                    };
                    timer.schedule(doAsynchronousTask, 0, 3000);
    

    onCreate

     receiver = new BroadcastReceiver() {
    
                    @Override
                    public void onReceive(Context context, Intent intent) {
    
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
    
                            int resultCode = bundle
                                    .getInt(Services.RESULT);
                            if (resultCode == getActivity().RESULT_OK) {
                                trainingStatus = bundle
                                        .getString(Services.RESPONSE);
                                if (Status.equalsIgnoreCase("finished")) {
    
                                    if (intent != null) {
                                        getActivity().stopService(intent);
                                    }
                                    alarm.cancel(pintent);
                                } else {
    
                                }
    
                        }
                    }
                };
    

    服务

    @Override
        protected void onHandleIntent(Intent intent) {
    
            Log.e("TAG", " Training services start");
    
            Bundle extras = intent.getExtras();
    publishResults(trainingStatus, resultInt);
    }
    private void publishResults(String response, int result) {
            Intent intent = new Intent(FILTER);
            intent.putExtra(RESPONSE, response);
            intent.putExtra(RESULT, result);
            sendBroadcast(intent);
        }
    

    【讨论】:

    • 最好解释你的答案,而不是简单地将一堆未注释的代码转储给用户。
    • 在片段中我使用广播接收器。 onResume 如果接收器得到正确的结果取消警报,我每 3 秒调用一次服务。我更新片段代码检查它
    猜你喜欢
    • 2015-12-31
    • 2020-03-06
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2021-03-15
    • 2023-03-31
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多