Android笔记二十九.Service组件入门(三).使用IntentService

package com.example.android_intentservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } //当启动Service,调用该方法执行相应代码 @Override public int onStartCommand(Intent intent, int flags, int startId) { long endTime = System.currentTimeMillis()+20*1000; System.out.println("onStart"); while(System.currentTimeMillis()<endTime) { synchronized(this) {try{wait(endTime-System.currentTimeMillis());}catch(Exception e){} } } System.out.println("—普通Service耗时任务执行完成—"); return START_STICKY; } }(4)\src\com\example\android_intentservice\MyIntentService.java实现:实现一个IntentService执行耗时任务(20s),观察是否导致ANR异常package com.example.android_intentservice;import android.app.IntentService;import android.content.Intent;public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } //IntentService会使用单独的线程来执行方法的代码 @Override protected void onHandleIntent(Intent intent) { //该方法内可以执行任何耗时任务,比如下载文件等,此处只是让线程暂停20s long endTime = System.currentTimeMillis()+20*1000; System.out.println("onStart"); while(System.currentTimeMillis()<endTime) { synchronized(this) {try{wait(endTime-System.currentTimeMillis());}catch(Exception e){} } } System.out.println("—IntentService耗时任务执行完成—"); }}

,去陌生的街角,去做一切我们曾经或现在也很想做的事情,

Android笔记二十九.Service组件入门(三).使用IntentService

相关文章:

你感兴趣的文章:

标签云: