2013-09-23 93 views
0

這是我的網絡運營服務。但它是拋出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) { 

     } 

    } 

可有人請幫我異步任務整合到相同的代碼。謝謝

+2

'getStories()'和'解析()的調用onStart()'需要在'doInBackground()'。實際上很簡單 - 如果你訪問網絡,它需要脫離UI線程。 'doInBackground()'運行UI。 – 323go

+0

我建議看看int IntentService。這篇文章可能對你有幫助。 http://stackoverflow.com/questions/15524280/service-vs-intent-service – Prmths

+0

雅..我明白這個方法需要在「doInBackground()」,但我有點混淆兩個「返回」聲明。你能告訴我一體化嗎?謝謝 – user45678

回答

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

    } 
} 

}

開始在一個活動的服務:startService(...)

+0

感謝Antho,但目前我不想更改我的整個代碼並使用相同的集成公式。謝謝,如果你能幫助我。 – user45678

0

從您的服務類進行網絡操作

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

}