【Android学习】Android服务之Service(3)--IntentService
IntentService是Service的子类,并增加了额外的功能。
对于Service:
1.Service不会专门启动一条单独的进程,Service与它所在的应用位于同一进程中。
2.Service也不是专门一条新的线程,因此不应该在Service中直接处理耗时的动作。
因此,如果开发者需要在Service中处理耗时任务,需要在Service中另外启动一条新的线程来处理耗时任务,就像在前面的BindService中,程序在BindService中的onCreate()方法中启动了一条新线程来处理耗时任务。
而对于IntentService来说,则不存在这种问题:IntentService会使用新的Worker线程来处理Intent请求,因此IntentService不会阻塞主线程,所以IntentService自己就可以处理耗时任务。
普通Service与IntentService的比较如下:
主页面:
public class IntentServiceTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startService(View source) { // 创建需要启动的Service的Intent Intent intent = new Intent(this, MyService.class); // 启动Service startService(intent); } public void startIntentService(View source) { // 创建需要启动的IntentService的Intent Intent intent = new Intent(this, MyIntentService.class); // 启动IntentService startService(intent); } }
MyService.java:
public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 该方法内执行耗时任务可能导致ANR(Application Not Responding)异常 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("---耗时任务执行完成---"); return START_STICKY; } }
MyIntentService.java:
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } // IntentService会使用单独的线程来执行该方法的代码 @Override protected void onHandleIntent(Intent intent) { // 该方法内可以执行任何耗时任务,比如下载文件等,此处只是让线程暂停20秒 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("---耗时任务执行完成---"); } }
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startService" android:text="@string/start_service"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startIntentService" android:text="@string/start_intent_service"/> </LinearLayout>
结果:
普通Service:
IntentService;
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。