这是我的网络运营服务。但它是抛出NetworkonMainThreadException,我明白Android的上层版本不允许在主线程下的网络操作。现在我想为此使用异步任务。我不确定哪些代码需要在服务类的异步任务下添加以实际完成代码。下面是我的服务代码:如何在Android服务中异步任务网络操作?
public class NewsTickerDataService extends Service {
@Override
public void onStart(Intent aIntent, int aStartId) {
super.onStart(aIntent, aStartId);
RemoteViews _views = buildUpdatedViews(this);
ComponentName _widget =
new ComponentName(this, NewsTicker.class);
AppWidgetManager _manager =
AppWidgetManager.getInstance(this);
_manager.updateAppWidget(_widget, _views);
}
@Override
public IBinder onBind(Intent aParamIntent) {
// not supporting binding
return null;
}
private RemoteViews buildUpdatedViews(Context aContext) {
List<Story> _stories = getStories();
RemoteViews _result = new RemoteViews(
aContext.getPackageName(),
R.layout.activity_main
);
if (_stories.isEmpty()) {
_result.setTextViewText(R.id.title,
"Sadly there's nothing to read today.");
} else {
_result.setTextViewText(
R.id.title, _stories.get(0).getTitle());
}
return _result;
}
private List<Story> getStories() {
try {
URL _url = new URL("http://search.twitter.com" +
"/search.atom?q=%23uml&" +
"result_type=mixed&count=5"
);
InputStream _in = _url.openStream();
return parse(new InputSource(_in));
} catch (Exception anExc) {
Log.e("NewsTicker", anExc.getMessage(), anExc);
return new ArrayList<Story>();
}
}
private List<Story> parse(InputSource aSource)
throws Exception {
SAXParserFactory _f = SAXParserFactory.newInstance();
SAXParser _p = _f.newSAXParser();
XMLReader _r = _p.getXMLReader();
AbstractParser _h = AbstractParser.newAtomParser();
_r.setContentHandler(_h);
_r.parse(aSource);
return _h.getStories();
}
}
异步任务代号:
public class YourAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
// your load work
//return myString;
}
@Override
protected void onPostExecute(String result) {
}
}
可有人请帮我异步任务整合到相同的代码。谢谢
'getStories()'和'解析()的调用onStart()'需要在'doInBackground()'。实际上很简单 - 如果你访问网络,它需要脱离UI线程。 'doInBackground()'运行UI。 – 323go
我建议看看int IntentService。这篇文章可能对你有帮助。 http://stackoverflow.com/questions/15524280/service-vs-intent-service – Prmths
雅..我明白这个方法需要在“doInBackground()”,但我有点混淆两个“返回”声明。你能告诉我一体化吗?谢谢 – user45678