安卓不允许在UI线程中发送网络请求,因此必须新启动一个线程。
如果我们在活动中new Thread,这样就会有问题,这个线程会随着活动的生命周期结束而结束,如果活动的命比这个线程短,活动死掉了,线程还没有进行完,然后也不幸
挂了,这样,获取数据的任务就相当于是失败了,这肯定是不可以的啊。所以我们需要使用一个后台进程,比如AsyncTask,但是这个AsyncTask也要能快速完成(最多几秒),
不过他也有的一个问题就是,如果用户选择屏幕,后台的那个AsyncTask没有执行完,又会新建一个AsyncTask,这就导致资源的浪费了,不过应该问题不大,我们还是要知道
这个AsyncTask的。最后就是IntentService,系统会根据情况停止IntentService。下面来一个个讲
doInBackground(Params...)
), and most often will override a second one (
onPostExecute(Result)
.)
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }这样使用:
new DownloadFilesTask().execute(url1, url2, url3);我们在sunshine工程中也新建了一个FetchWeatherTask
onHandleIntent()
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
Intent alarmIntent = new Intent(getActivity(), SunShineService.AlarmReceiver.class); alarmIntent.putExtra(SunShineService.LOCATION_QUERY_EXTRA, location); PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, alarmIntent, PendingIntent.FLAG_ONE_SHOT); AlarmManager am = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pi);
static public class AlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Intent sendInentd = new Intent(context, SunShineService.class); String location = intent.getStringExtra(SunShineService.LOCATION_QUERY_EXTRA); sendInentd.putExtra(SunShineService.LOCATION_QUERY_EXTRA, location); context.startService(sendInentd); } }