zoukankan      html  css  js  c++  java
  • 关于IntentService 用法

    IntentService就是一个后台处理类,它继承了Service并且对其封装。我们可以向他发送多个请求Intent。IntentService会把所有收到的Intent请求放到队列中。逐个处理,他会为每个请求创建一个单独的工作线程。当处理完队列中所有的Intent请求后。就会终止自己。

    在什么情况下使用IntentService呢?

    当我们要在Android上的实现后台处理任务主要有三种实现方式:

    (1)是按照常规的Java方式,自己写线程(例如Thread)

    (2)使用SDK封装好的后台任务类AsyncTask

    (3)使用Service。

    线程和AsyncTask都是和Activity的生命周期绑定的,一旦Activity被销毁它们也随着销毁了,但Service有自己的独立生命周期。

    当一项任务分成几个子任务,子任务需要按顺序先后执行。利用线程,给每一个子任务开启一个线程是可以达到这个目的的,但是每个线程必须去手动控制,而且得在一个子线程执行完后,再开启另一个子线程。或者,全部放到一个线程中让其顺序执行。这样都可以做到,但是,如果这是一个后台任务,就得放到Service里面,由于Service和Activity是同级的,所以,要执行耗时任务,就得在Service里面开子线程来执行。那么,有没有一种简单的方法来处理这个过程呢,答案就是IntentService。

    例子:

    public class MyIntentService extends IntentService {
    
        private static int num = 0;
        Handler handler = new Handler();
    
        /**
         * 这里需要注意一下,Eclipse默认生成的是带参数的构造函数,但是这样会引起异常的
         * java.lang.InstantiationException: can't instantiate class..... no empty constructor 错误
         */
        public MyIntentService() {
            super("test");
        }
    
        @Override
        protected void onHandleIntent(Intent arg0) {
            for (int i = 1; i < 11; i++) {
                num += i;
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MyIntentService.this, String.valueOf(num),
                            Toast.LENGTH_SHORT).show();
                }
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

     在Activity中调用

    btn2.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //发送第一个Intent请求
                    Intent intent = new Intent("myintentservice");
                    startService(intent);
                    
    //发送第二个Intent请求
                    Intent intent2 = new Intent("myintentservice");
                    startService(intent2 ); 
    } });

     关于IntentService的java.lang.InstantiationException错误:

    http://www.cnblogs.com/helloandroid/articles/2208154.html

  • 相关阅读:
    Odd sum CodeForces
    Chips CodeForces
    Secrets CodeForces
    Voting CodeForces
    Jury Meeting CodeForces
    Planning CodeForces
    Maxim Buys an Apartment CodeForces
    Chemistry in Berland CodeForces
    Monitor CodeForces
    Four Segments CodeForces
  • 原文地址:https://www.cnblogs.com/ywtk/p/3818907.html
Copyright © 2011-2022 走看看