• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Ocean123123
博客园    首页    新随笔    联系   管理    订阅  订阅

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();
    }

}

 

posted @ 2019-06-14 10:19  Ocean123123  阅读(207)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3