前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android-Service奔溃-使用IntentService

Android-Service奔溃-使用IntentService

作者头像
圆号本昊
发布2021-09-24 11:56:49
3360
发布2021-09-24 11:56:49
举报
文章被收录于专栏:github@hornhuang

问题:

激发startService()方法,该方法将会使用将会启动MyService去执行耗时任务,将会导致UI线程被阻塞(程序界面失去响应,即ANR异常)

解决:

通过启动IntentService 来启动MyIntentService,虽然MyIntentService也需要执行耗时任务,但由于MyIntentService会使用单独的worker线程,因此MyIntentService不会阻塞前台的UI线程。

ANR异常:

IntenService:

(点击IntentService不发生异常,点击Service发生ANR异常)

对了方便看出两者不同,这里进行对比:

首先我们先定义一个Service:

代码语言:javascript
复制
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

代码语言:javascript
复制
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");
    }
}

最后我们在主活动中启动他们进行对比:

代码语言:javascript
复制
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:进行对接

【如果本篇文章对您有帮助,欢迎关注我获得更多资讯】

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/01/14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 解决:
    • ANR异常:
      • IntenService:
      • 对了方便看出两者不同,这里进行对比:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档