A)MainActivity部分的代码
1 package com.example.cms.intentservice; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 9 public class MainActivity extends AppCompatActivity { 10 private Button startService; 11 private Button startIntentService; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 startService= (Button) findViewById(R.id.Service); 18 startIntentService= (Button) findViewById(R.id.IntentService); 19 startService.setOnClickListener(new View.OnClickListener() { 20 @Override 21 public void onClick(View v) { 22 startService(); 23 } 24 }); 25 startIntentService.setOnClickListener(new View.OnClickListener() { 26 @Override 27 public void onClick(View v) { 28 startIntentService(); 29 } 30 }); 31 } 32 public void startService() { 33 Intent intent = new Intent(this, MyService.class); 34 startService(intent); 35 } 36 public void startIntentService(){ 37 Intent intent=new Intent(this,MyIntentService.class); 38 startService(intent); 39 } 40 }
B)MyService部分的代码
1 package com.example.cms.intentservice; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 import android.support.annotation.Nullable; 7 8 /** 9 * Created by CMS on 2016/3/28. 10 */ 11 public class MyService extends Service { 12 @Nullable 13 @Override 14 public IBinder onBind(Intent intent) { 15 return null; 16 } 17 18 @Override 19 public int onStartCommand(Intent intent, int flags, int startId) { 20 //使用线程暂停的方式 模拟耗时任务 暂停20秒 21 //普通的Service的执行会堵塞主线程 因此执行此方法会出现ANR异常 22 long endTime=System.currentTimeMillis()+20*1000; 23 System.out.println("onStart"); 24 while(System.currentTimeMillis()<endTime){ 25 synchronized (this){ 26 try { 27 wait(endTime-System.currentTimeMillis()); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 } 32 } 33 System.out.println("---耗时任务执行完成----"); 34 return START_STICKY; 35 } 36 }
C)MyIntentservice部分的代码
package com.example.cms.intentservice; import android.app.IntentService; import android.content.Intent; import android.content.IntentSender; /** * Created by CMS on 2016/3/28. */ public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { //IntentService会使用单独的线程来执行此方法的代码 //不会阻塞主线程 所以不会出现ABR异常 long endTime=System.currentTimeMillis()+20*1000; System.out.println("onHandleIntent"); while(System.currentTimeMillis()<endTime){ synchronized (this){ try { wait(endTime-System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("耗时任务执行完成"); } }