IntentService使用

说实话,对于这个类在我实际工作中并没有用到过,通常也只是用了它的父类Service,通过官方文档可以看出类的层次结构:

而在今年的一次面试当中,有个面试官提起了它,所以虽说目前还没有真实在项目中用它,但是有必要先了解一下它的用法,在大脑中有一定的印象,以便将来真正能用到时则直接参考既可。

对于这个类的使用当然不用自己摸索,可以参考该博文:http://blog.csdn.net/hudashi/article/details/7986130

先依照官网的介绍有个大致的了解【来自银家博文】:

下面来把博文中说的例子给运行看下效果:

先声明服务MyIntentService:

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

    public MyIntentService() {
        super("com.example.layouttest.MyIntentService");
        Log.i(TAG, this + " is constructed");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        Log.i(TAG, "begin onHandleIntent() in " + this);
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "end onHandleIntent() in " + this);
    }

    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, this + " is destroy");
    }
}

然后再主界面去调这个服务MainActivity:

public class MainActivity extends Activity implements OnClickListener {

    // views
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) {
        Intent intent = new Intent(this, MyIntentService.class);
        startService(intent);// 连续发起了三次请求
        startService(intent);
        startService(intent);
    }

}

下面来看下运行的效果:

从运行效果可以发现跟Service的一个很大的区别在于,同时发出多个请求之后,当最后一个请求被处理,则整个Service也退出了,关于它真正的使用场景,待在实际工作中用到了再来总结,目前先学会怎么用它~

 

总结:

在网上搜到了一个关于IntentService的一个特点,我觉得有几点写出了它的好处:

posted on 2015-02-28 16:22  cexo  阅读(422)  评论(0编辑  收藏  举报

导航