zoukankan      html  css  js  c++  java
  • 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();
        }
    
    }
  • 相关阅读:
    CSS实现背景透明,文字不透明(兼容各浏览器)
    JQUERY SCROLL PATH自定义滚动路径
    Truffle3.0集成NodeJS并完全跑通(附详细实例,可能的错误)
    truffle的调用nodeJs的问题
    Truffle基础篇-Truffle做什么的?怎么安装?
    以太坊智能合约开发笔记
    day02 智能合约
    remix无法安装的解决方案
    基于eth快速发行自己的数字货币
    remix-ide的三种使用方式
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/11021986.html
Copyright © 2011-2022 走看看