2012-06-29 26 views
0

我寫了一些代碼來從AsyncTask開始一項服務,我可以在調試模式下看到該服務已啓動。看不到我的AsyncTask啓動和服務

AsyncTask在後臺啓動該服務的代碼如下,

protected String doInBackground(String... params) { 
//starts service number activite 
MyResultReceiver resultReceiver = new MyResultReceiver(null); 
Intent intent = new Intent(context, MyService.class); 
intent.putExtra("receiver", resultReceiver); 
context.startService(intent); 

和中的service是:

public class MyService extends Service{ 


    ResultReceiver resultReceiver; 


     @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     //resultReceiver = intent.getParcelableExtra("receiver"); 


     resultReceiver = intent.getParcelableExtra("receiver"); 
     Bundle data = new Bundle(); 
      data.putString("key",getActivityUrl()); 
     resultReceiver.send(2, data); 

     resultReceiver.send(2,null); 
    return START_STICKY; 
    } 



     @Override 
      public IBinder onBind(Intent intent) { 
      return null; 
      } 

    public String getActivityUrl() { 
    String str = null; 
     try{ 

URL url = null; 
     try { 
      url = new URL("http://www.google.com"); 
     } catch (MalformedURLException ex) { 
      Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     // Read all the text returned by the server 
     BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

     while ((str = in.readLine()) != null) { 
      // str is one line of text; readLine() strips the newline character(s) 
     } 
       //all is ok 

     in.close(); 

    }  catch (IOException ex) { 
     Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex); 
    }finally{ stopSelf(); 
    } 

    //resultReceiver.send(100,null); 

    return str; 
} 

}

另一個問題:我如何發送一個字符串,而不僅是一個int與resultReceiver.send

回答

1

我該如何發送字符串,而不是int resultReceiver.send?

只需創建Bundle並放入String即可。

Bundle data = new Bundle(); 
data.putString("key", data); 
resultReceiver.send(2, someData); 


注:僅限send()方法的肯定,第一個參數想象onReceiveResult方法resultCode爲

+0

你rae做壞事添加這裏的代碼。 – Sajmon

+0

好,但爲什麼我的服務沒有啓動? –

+0

爲什麼你使用Asynctask和ResultReceiver? AsyncTask具有onProgressUpdate方法,用於更新您的用戶界面也從你的代碼即時通訊很少困惑,骯髒的書面。 – Sajmon