简体   繁体   English

如何在Alarmmanager中运行asynctask?

[英]How to run an asynctask inside an Alarmmanager?

I have an asynctask which consumes a webservice. 我有一个消耗Web服务的asynctask。 Now I need to execute the asynctask once a day, at a certain hour. 现在,我需要每天在某个小时执行一次异步任务。 What I want to do is call doinbackground event of the asynctask inside the AlarmManager. 我想做的是在AlarmManager中调用asynctask的doinbackground事件。 I have read about using AlarmManager but there is no documentation about using it with asynctask. 我已经阅读了有关使用AlarmManager的信息,但是没有有关将其与asynctask一起使用的文档。 Am I going to the right direction? 我会朝正确的方向前进吗? Any advice will highly apreciate 任何建议都将非常重要

Step1: Create an alarm manager which runs once in a day. 步骤1:创建每天运行一次的警报管理器。 Time you can set according to your requirements. 您可以根据需要设置时间。 Here I set it at 7am. 在这里,我将其设置为上午7点。

int REPEATING_TIME = 24 * 60 * 60 * 1000;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 06);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Intent i = new Intent(context, DemoService.class);
        PendingIntent pi = PendingIntent.getService(context,
                202, i,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), REPEATING_TIME, pi);

Step 2 : Create an asynctask class and do the background operation there you want to perform. 第2步:创建asynctask类,并在其中执行要执行的后台操作。

public class LoadData extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... params) {

        return "response";
    }

}

Step 3 : Create a class which extends the Service. 步骤3:创建一个扩展服务的类。

    public class DemoService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            new LoadData(){}protected void onPostExecute(String result){
// anything you want to perform onPost.
};}.execute("API URL");

            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

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

    }

Hope it will solve your problem. 希望它能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM