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
?
你rae做壞事添加這裏的代碼。 – Sajmon
好,但爲什麼我的服務沒有啓動? –
爲什麼你使用Asynctask和ResultReceiver? AsyncTask具有onProgressUpdate方法,用於更新您的用戶界面也從你的代碼即時通訊很少困惑,骯髒的書面。 – Sajmon