如何在Android服务中异步任务网络操作?

时间:2013-09-23 14:18:52

标签: android asynchronous service

这是我的服务,负责网络运营。但它正在抛出NetworkonMainThreadException,我理解android上层版本不允许在主线程下进行网络操作。现在我想为此目的使用异步任务。我不确定我需要在Service Class的Async Task下添加哪些代码来实际完成代码。以下是我的服务代码:

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) {

        }

    }

有人可以帮助我将Async Task集成到相同的代码中。感谢

2 个答案:

答案 0 :(得分:0)

是的,我也建议使用IntentService!

IntentService示例

public class MyService extends IntentService {

private int STOP_DOWNLOAD = false;
public static int UPDATE_PROGRESS = 0;

public MyService() {
    super("myservice");
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
protected void onHandleIntent(Intent intent) {

    // Network Task : download ?

    // Send some data to the receiver
    Bundle resultData = new Bundle();
    resultData.putInt("progress", progress);
    receiver.send("update", resultData);
}

private void stopDownload() {
    this.STOP_DOWNLOAD = true;
    // Stop the download : use this boolean into onHandleIntent
}

}

接收者

public class MyReceiver extends ResultReceiver {

Context context;

public MyReceiver(Context mContext) {
    super(handler);
    context = mContext;
}

@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
    super.onReceiveResult(resultCode, resultData);

    if (resultCode == "update") {


        String something = resultData.getString(MyService.SOMETHING);

    }
}

}

在Activity:startService(...)

中启动服务

答案 1 :(得分:0)

从服务类的onStart()进行网络操作

        YourAsyncTask.execute(url);

异步任务代码

    public class YourAsyncTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        // your load work
        DefaultHttpClient client = new DefaultHttpClient();
         HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse execute = client.execute(httpGet);
      InputStream content = execute.getEntity().getContent();

      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
      String s = "";
      while ((s = buffer.readLine()) != null) {
        response += s;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }



  return response;
        //return myString;
    }

    @Override
    protected void onPostExecute(String result) {
       //HERE CALL YOUR PARSE METHOD

       //AFTER PARSING CALL buildUpdatedViews(Context aContext , stories)
    }

}