IntentService下载任务

onHandleIntent开启一个线程按顺序处理任务,不适合做大量任务

public class MainActivity extends AppCompatActivity {


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.image);

        Intent intent = new Intent(MainActivity.this, MyIntentService.class);
        intent.putExtra("path", "http://www:xxx.xxx");
        startService(intent);
        startService(intent);
        startService(intent);

    }

            }

开启3个任务,排队执行,过后服务自动销毁,所以不要stopService

public class MyIntentService  extends IntentService {
    private static final String TAG = "TAG";

    public MyIntentService() {
        super("MyIntentService");
        Log.d(TAG, "MyIntentService: " + Thread.currentThread().getName());

    }


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


    @Override
    protected void onHandleIntent( Intent intent) {
        //耗时操作  不用再单独的开启线程
        Log.d(TAG, "MyIntentService: " + Thread.currentThread().getName());
        String path = intent.getStringExtra("path");
        System.out.println(TAG+path);
        downloadTask(path);

    }

    private void downloadTask(String path) {
        Log.d(TAG, "downloadTask: ");
        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    /**
     * 当某个请求需要处理时,这个方法会在工作者线程被调用
     * 一次仅仅会有一个请求被处理,但是处理过程会运行在工作者线程(独立于其他应用程序逻辑运行)。
     * 因此,如果某段代码需要执行很长时间,它会阻塞住其他提交到该IntentService的请求
     * ,但是不会阻塞住其他任何东西。当所有的请求被处理完成之后,IntentService会停止它自身,
     * 因此你不应该手动调用stopSelf()方法。
     */

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

}
原文地址:https://www.cnblogs.com/Ocean123123/p/11021986.html