Android使用IntentService执行耗时任务

概述

IntentService也是Service的子类,它比普通Service增加了额外的功能:
  1. IntentService会创建单独的work线程来处理所有的Intent请求。
  2. IntentService会创建单独的work线程来处理onHandleIntent()方法实现的代码,因此开发者无需处理多线程的问题。
  3. 当所有请求处理完成时,IntentService会自动停止。
  4. 无需重写onBind().onStartCommand()方法,只要重写onHandleIntent()即可

java代码

activity:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public  class MainActivity extends Activity {
    Intent intentService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         intentService = new Intent(this, MyIntentService.class);

    }
    public void intentService(View v){
        Toast.makeText(this, "intentServiceStart", Toast.LENGTH_SHORT).show();
        startService(intentService);
    }
}

IntentService:

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("name");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        long endTime=System.currentTimeMillis()+20*1000;
        while(System.currentTimeMillis()<endTime){
            synchronized(this){
                try {
                    wait(endTime-System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.v("sssssy","耗时任务执行完成");
            }
        }
    }
}

总结

synchronized(),并发,同步的意思。  
当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值