我Service
让它在后台运行,使用从互联网收集数据AsyncTask
并将它们存储在Shared Preferences
. 即使工作已经完成,AsyncTask
它仍然冻结了我的主要活动。
这是服务的代码:
public class GetterService extends Service {
SharedPreferences.Editor editor;
HashMap<Integer,String> links = new HashMap<Integer,String>();
@Override
public void onCreate() {
editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
populateLinks();
}
private void populateLinks(){
// Here I add links to HashMap
}
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "GetterService ON BIND", Toast.LENGTH_LONG).show();
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "GetterService ON DESTROY", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
doTasks();
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this, "GetterService ON UNBIND", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
private void doTasks(){
for (Integer in : links.keySet()) {
Document doc = null;
try {
doc = new NetTask().execute(links.get(in)).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (doc != null) {
Elements names = doc.select("strong, li");
if(names != null && names.size() > 0) {
for (int j = 0; j < names.size(); j++) {
editor.putString("header"+j, names.get(j).text().toString());
}
}
editor.commit();
}
}
}
public class NetTask extends AsyncTask<String, Integer, Document>
{
@Override
protected Document doInBackground(String... params)
{
Document doc = null;
try {
doc = Jsoup.connect(params[0]).timeout(5000).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
}
}
这是我从主要活动启动服务的方式:
Intent startServiceIntent = new Intent(this, GetterService.class);
this.startService(startServiceIntent);