激发startService()方法,该方法将会使用将会启动MyService去执行耗时任务,将会导致UI线程被阻塞(程序界面失去响应,即ANR异常)
通过启动IntentService 来启动MyIntentService,虽然MyIntentService也需要执行耗时任务,但由于MyIntentService会使用单独的worker线程,因此MyIntentService不会阻塞前台的UI线程。
(点击IntentService不发生异常,点击Service发生ANR异常)
首先我们先定义一个Service:
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//改方法内执行ANR(Application Not Responding)异常
Long endTime = System.currentTimeMillis() + 20 * 1000;
Log.v("myService","onStart");
while (System.currentTimeMillis() < endTime){
synchronized (this){
try {
wait(endTime - System.currentTimeMillis());
}catch (Exception e){
}
}
}
Log.v("myService","--耗时任务执行完成--");
return START_STICKY;
}
}
为了对比我们再定义一个IntentService
public class MyIntentService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "com.example.a30797.servietest.action.FOO";
private static final String ACTION_BAZ = "com.example.a30797.servietest.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.example.a30797.servietest.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.example.a30797.servietest.extra.PARAM2";
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
//该方法内可以执行耗时任务
long endTime = System.currentTimeMillis() + 20 * 1000;
Log.v("myService","onStartCommand");
while (System.currentTimeMillis() < endTime){
synchronized (this){
try {
wait(endTime - System.currentTimeMillis());
}catch (Exception e){
}
}
}
Log.v("myService","耗时任务执行完成");
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo(String param1, String param2) {
// TODO: Handle action Foo
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz(String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException("Not yet implemented");
}
}
最后我们在主活动中启动他们进行对比:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View Scource){
//需要启动的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);
}
}
注:这里的两个方法在布局文件的Button中用onClick:进行对接
【如果本篇文章对您有帮助,欢迎关注我获得更多资讯】