您的位置:首页 > 移动开发 > Android开发

Android 四大组件之特殊Service(IntentService)的使用

2017-04-26 17:32 585 查看
在Service中,通常是不需要同时处理多个请求的,在这种情况下,使用IntentService或许是最好的选择。为什么呢?下面的这个问题给出了答案。

IntentService如何使用?和Service有什么区别? 

IntentService里面是默认自带一条线程的,无需自己去new子线程,而且是和主线程分离的,使用的时候只需要处理onHandleIntent()这个方法即可。不需要去写onCreate(),也不需要去写onStartCommand(),而且在任务执行结束后,会自行调用stopSelf()方法来关闭Service。IntentService适用于单线程去完成任务,而且不会阻塞主线程。

MainActivity代码,很简单,启动Service:
package com.example.lenovo.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

/**
* 开启服务,进行下载
*/
public void downLoad(View view){
startService(new Intent(this,MyService.class));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

MyService代码:
package com.example.lenovo.demo;

import android.app.IntentService;
import android.content.Intent;

/**
* Created by shan on 2016/7/23.
*
*/
public class MyService extends IntentService {
/**
* Creates an IntentService.  Invoked by your subclass's constructor.
* 这里需要一个空的构造方法
*/
public MyService() {
super("");
}

@Override
protected void onHandleIntent(Intent intent) {
//无需new子线程,直接进行耗时操作:do something
//任务完成后也无需关闭Service,源码内部已经实现stopSelf()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

最后,配置清单文件,静态注册Service,添加所需的权限即可。具体的耗时代码就不写了~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐