IntentService的使用

IntentService是一个基于Service的一个类,用来处理异步的请求。你可以通过startService(Intent)来提交请求,该Service会在需要的时候创建,当完成所有的任务以后自己关闭,且请求是在工作线程处理的。有两个好处,一方面不需要自己去new Thread了;另一方面不需要考虑在什么时候关闭该Service了。

public class MyService extends IntentService {
    public final static String ACTION_UPLOAD_IMG = "upload";
    public final static String UPLOAD_IMG_COMPLETE = "upload complete";


    public MyService() {
        super("");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG","onCreate");
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG","onStart");
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Log.d("TAG","onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_UPLOAD_IMG.equals(action)) {
                uploadImg();
            }
        }
    }

    private void uploadImg() {
        try {
            //模拟上传耗时
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        EventBus.getDefault().post(UPLOAD_IMG_COMPLETE);
    }

    @Override
    public void onDestroy() {
        Log.d("TAG","onDestroy");
    }
}

继承IntentService,然后复写onHandleIntent方法,根据传入的intent来选择具体的操作。
与startService一样,若当前intentService未开启,会调用onCreate和onStart方法,若已经开启了,则只执行onStart方法,需要注意的是,intentService会在任务执行完成后自动销毁,如果你第二次开启intentService之前,intentService的任务已经执行完了,会重新调用onCreate和onStart方法开启新的intentService对象。
Activity

@Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.start:
                intent = new Intent(this, MyService.class);
                intent.setAction(MyService.ACTION_UPLOAD_IMG);
                startService(intent);
                Log.d("TAG","start upload");
                break;
        }

}

@Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMessage(String msg) {
    if (msg.equals(MyService.UPLOAD_IMG_COMPLETE)) {
    Log.d("TAG","upload complete");
    }
}

Activity中,每当我点击一次按钮调用addTask,就回模拟创建一个任务,然后交给IntentService去处理。当所有的任务完成的时候,后台的Service会退出,不会占据任何内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值