关于Intentsetvice

什么是IntentService,IntentService是继承于Service并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService的方式和启动传统Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们去手动控制。另外,可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。
 
所有请求都在一个单线程中,不会阻塞应用程序的主线程(UI Thread),同一时间只处理一个请求。
 

public class Loginservice extends IntentService{

public Loginservice(String name) {
super(name);
}
public Loginservice() {

//必须实现父类构造方法
super("Loginservice");
}
@Override
protected void onHandleIntent(Intent intent) {
final String userID=intent.getExtras().getString("userID");
boolean isLogined=intent.getExtras().getBoolean("isLogined");
if (!TextUtils.isEmpty(userID) && isLogined) {
AsyncRunner.HttpGet(new BaseRequestListener() {

@Override
public void onBarfooError(BarfooError e) {
super.onBarfooError(e);
}

@Override
public void onRequesting() throws BarfooError, JSONException {
Bundle bundle = new Bundle();
bundle.putString("userId", userID);
JSONObject response = BaseHttp.httpGet(BaseHttp.build_api(
"http://222.175.186.6:8214/GetChannelByUId", bundle));
LogUtil.i("getUserChannelsFromServer:" + response.toString()+"==========");

String selected = response.getJSONObject("Data").getString("selected");
String unselected = response.getJSONObject("Data").getString("unSelected");
String[] selectedStr = selected.split(",");
String[] unselectedStr = unselected.split(",");

// 由于服务器返回的栏目只是栏目ID,这里需要转化成栏目实体
ArrayList<Channel> selectedChannels = longinUtil.getUserSelectedChannels(selectedStr);
ArrayList<Channel> unselectedChannels = longinUtil.getUserUnselectedChannels(unselectedStr);
longinUtil.updateUserChannels(selectedChannels, unselectedChannels);
}

});
}
}

 

//启动Intentservice与service一样

startService(intent);

//注册service

<service android:name=".service.Loginservice">
<intent-filter >
<action android:name="urun.news.service.Loginservice"/>
</intent-filter>
</service>

posted @ 2015-06-11 10:49  星耀1  阅读(307)  评论(0编辑  收藏  举报