IntentService的用法,对比Service它会按顺序执行,不会像Service一样并发执行。

package com.lixu.intentservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        for(int i=0;i<20;i++){    
            Intent intent=new Intent(this,MyAppService.class);
            intent.putExtra(Changliang.KEY, i+"");
            
            startService(intent);
        }
    }
 //不要忘了关闭服务
    @Override
    protected void onDestroy() {
        Intent intent=new Intent(this,MyAppService.class);
        stopService(intent);
        super.onDestroy();
    }


}
package com.lixu.intentservice;

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

public class MyAppService extends IntentService{
    //构造方法要修改
    public MyAppService() {
        super("lixu");
    }

    
    @Override
    protected void onHandleIntent(Intent intent) {
        
        String str=intent.getStringExtra(Changliang.KEY);
        Log.e("MyAppService","内容"+ str);
        int content=0;
        final int A=content++;
        Log.e("MyAppService","线程"+ A+"开始执行");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.e("MyAppService", "线程"+ A+"结束");
        
    }

}
原文地址:https://www.cnblogs.com/labixiaoxin/p/4949197.html