在android asyncTask中重复运行doInBackground

时间:2014-03-15 12:33:13

标签: android user-interface background-process

我想以特定的间隔重复从数据库中获取用户,然后在UI上对它们执行某些操作。我知道asynchTask只能执行一次,但我希望它反复运行以获取新用户的数据。我想知道有没有办法做到这一点,即在特定间隔后重复获取用户,然后在UI上用它们做一些事情??? 这是有效的代码..

while(true) {
new plottingTask().execute("");
Thread.sleep(10000);
}

1 个答案:

答案 0 :(得分:2)

请检查此问题:How to execute Async task repeatedly after fixed time intervals

已多次询问过。

无限循环不是一个好方法!

如果您想要在Activity处于后台/未投放时获取数据,那么Service将是更好的方法。

public class MyService extends Service {

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

        MyAsyncTask MyTask = new MyAsyncTask ();
        MyTask.execute();

        return Service.START_STICKY; // if android our the user kills the Service it will restart 
    }
}

    private class MyAsyncTask extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... params) {
            // do your long/network operation
        }

        @Override
        protected void onPostExecute(String result) {

            // send Intent to BroadcastReceiver in MainActivity.class to know the service  finished its task once
            Intent finished = new Intent("yourPackage.DOWNLOADCOMPLETE");
            sendBroadcast(finished);
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

在您的MainActivity中添加一个BroadcastReceiver:

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new ResponseReceiver();
    registerReceiver(receiver, filter);
}

// notify when operation in Service finished
private ResponseReceiver receiver;

public class ResponseReceiver extends BroadcastReceiver {
    public static final String ACTION_RESP = "yourPackage.DOWNLOADCOMPLETE";

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

        // do stuff if Service finished its task at least once
    }
}

使用AlarmManager每隔60秒启动一次Servive:

// refresh every 60 seconds in MyService.java
Calendar cal = Calendar.getInstance();
Intent  intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 60 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent);

startService(intent);

在AndroidManifest.xml中,您必须注册服务:

<service
    android:enabled="true"
    android:name=".MyService"
    android:label="your Service Name"> 
</service>
如果您导航到在Android中运行应用程序,将显示

android:label="your Service Name"