看不到我的AsyncTask启动和服务

时间:2012-06-29 11:54:14

标签: android service android-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);

和服务是:

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

}

另一个问题:如何发送字符串,而不仅仅是resultReceiver.send

的int

1 个答案:

答案 0 :(得分:1)

  

如何使用resultReceiver.send发送字符串而不仅仅是int?

只需创建Bundle并输入String

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


注意:只有当然,send()方法的第一个参数为onReceiveResult方法设想 resultCode