【问题标题】:how to get parametars from Service to AsyncTask如何从 Service 获取参数到 AsyncTask
【发布时间】:2012-06-22 13:08:37
【问题描述】:

我有一个 AsyncTask 并且在后台我想启动服务以从 url 获取文本。

我需要从服务中知道它何时完成工作并从中获取一些文本并继续 AsyncTask。 但我不知道如何从 Service 获取参数到 AsyncTask 并知道它是否完成。

我在 AsyncTask 上的代码是:

    protected String doInBackground(String... params) {
    //starts service number activite
    Intent serviceIntent = new Intent();
    serviceIntent.setAction("services.conServise");
    context.startService(serviceIntent);

return null;
}

服务代码:

    public void onStart(Intent intent, int startId) {

    // Create some random data
           try{
      URL url = new URL("http://hostname:80/index.html");

        // Read all the text returned by the server
  BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
     str is one line of text; readLine() strips the newline character(s)
        }
        activitNum = Integer.parseInt(str);
        in.close();

    } catch (MalformedURLException e) {
    } catch (IOException e) {
statusCon=-1;

    }finally{stopSelf();}


    super.onStart(intent, startId);
}

感谢您的帮助!

【问题讨论】:

    标签: android service android-asynctask


    【解决方案1】:

    Service 中的代码可以很容易地写在doInBackground() 方法中时,为什么要启动ServicedoInBackground() 在非 UI 线程上运行,旨在执行此类网络活动。因此,我建议您在 doInBackground() 本身中执行所有从网络获取数据的活动,而不是启动 Service

    【讨论】:

    • 如果应用程序在后台运行?
    • 在你的问题中你说你想暂停方法doInBackground()直到服务返回。现在你为什么还要停止非 UI 后台线程呢?由于它不会阻塞 UI,因此它可能需要任何时间来运行。如果您希望它在应用程序进入后台后运行,您可以单独启动 Service 或者在 onPostExecute() 中。
    猜你喜欢
    • 2011-11-13
    • 2020-08-28
    • 2018-03-29
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多