在sdk 21之上每5分钟运行一次后的运行方法

时间:2017-02-02 12:41:15

标签: java android service alarmmanager handler

正如我读到的那样无论你在闹钟管理器中定义的是什么时间段,它都会在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分钟后执行一次。 / p>

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

2 个答案:

答案 0 :(得分:0)

使用handler和timertask

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
}

答案 1 :(得分:-1)

alaram setReating not work api 19所以你使用handler来手动重复进程。参考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);
    }