从BroadcastReceiver中的AsyncTask返回字符串

时间:2015-01-18 15:41:03

标签: java android android-asynctask

我一整天都在努力,但我似乎无法弄明白。我试图从BroadcastReceiver中的AsyncTask返回一个字符串,但我不知道如何正确地做到这一点(Java新手)。我有一个访问互联网并读取文本文件的应用程序,这个文本文件是一个长字符串。我将字符串分隔成一个数组并以这种方式使用它的内容。在BroadcastReceiver中,我想每10-60分钟从气象站广播(更新)温度,具体取决于用户在通知栏上设置的内容。

我应该使用Thread而不是AsyncTask吗? 我得到的错误是以下行:

  

String output = new GetWeatherValues()。execute(weburi);

我还尝试了以下注释掉的代码:

  

// GetWeatherValues clientraw = new GetWeatherValues();

     

// clientraw.doInBackground(weburi);

以下是我的班级,请帮助,我搜索了很多但仍然没有结果。

public class UpdateFrequency extends BroadcastReceiver {

// Notification Text Elements
private final CharSequence tickerText = "Weather Updated";
private CharSequence contentTitle = "Weather at ";
private final CharSequence contentText = "Current Temperature is ";

final String http = "http://";
final String clientraw = "/clientraw.txt";
String weburi, webUrl;

// Notification Action Elements
private Intent notificationIntent;
private PendingIntent mContentIntent;

// Notification ID to allow for future updates
private static final int MY_NOTIFICATION_ID = 1;

final String PREFS_NAME = "SettingsFile";

SharedPreferences settings;
public String[] parts;

public static final String WebAddress = "webAddressKey";


@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent) {

    Log.e("log_etag", "Entered Update Frequency");

    settings = context.getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    if (settings.contains(WebAddress)) {
        webUrl = settings.getString(WebAddress, "");
        weburi = http + webUrl + clientraw;
        Log.e("log_etag", "WEB URL Frequency " + weburi);
    }

//      GetWeatherValues clientraw = new GetWeatherValues(); 
//      clientraw.doInBackground(weburi);

    String output = new GetWeatherValues().execute(weburi);

    String[] parts = output.split(" ");

    ArrayList<String> clientRawData = new ArrayList<String>();
    clientRawData.addAll(Arrays.asList(parts));

    //Time of last update from weather station.
    contentTitle = contentTitle + parts[29] + ":" + parts[30]; 

    Log.e("log_etag", "Content Title " + contentTitle);

    // The Intent to be used when the user clicks on the Notification View
    notificationIntent = new Intent(context, MainActivity.class);

    // The PendingIntent that wraps the underlying Intent
    mContentIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    // Build the Notification
    Notification.Builder notificationBuilder = new Notification.Builder(
            context).setTicker(tickerText)
            .setSmallIcon(android.R.drawable.stat_sys_warning)
            .setAutoCancel(true).setContentTitle(contentTitle)
            .setContentText(contentText).setContentIntent(mContentIntent);


    // Get the NotificationManager
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Pass the Notification to the NotificationManager:
    mNotificationManager.notify(MY_NOTIFICATION_ID,
            notificationBuilder.build());
}



private class GetWeatherValues extends AsyncTask<Void, Integer, String> {

    @Override
    protected String doInBackground(Void... params) {

                    try {

                        HttpClient httpclient = new DefaultHttpClient();
                        // get url data
                        HttpPost httppost = new HttpPost(weburi);
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();

                        InputStream webs = entity.getContent();
                        // convert response to string
                        try {
                            final BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(webs, "iso-8859-1"),
                                    8);

                            // read one line of code, file is one whole string.
                            try {

                                String returnData = reader.readLine();
                                webs.close();
                                return returnData;

                            } catch (Exception e) {
                                Log.e("log_tag",
                                        "Error in displaying textview "
                                                + e.toString());
                                e.printStackTrace();
                            }

                        } catch (Exception e) {
                            Log.e("log_tag",
                                    "Error converting string " + e.toString());
                        }
                    } catch (Exception e) {
                        Log.e("log_tag",
                                "Error in http connection " + e.toString());

                } 
        return null;
    }
}
}

1 个答案:

答案 0 :(得分:1)

你可以做的是在异步任务中覆盖onPostExecute(),看一下How to use AsyncTask correctly in Android的这个链接

onPostExecute()允许在UI线程上处理你的东西。

在这里你可以访问你的String(String returnData)

你也可以从async-task返回值,看看这个链接How to handle return value from AsyncTask 但我更愿意为你而不是那个我会有点复杂

一段代码

private class ABC extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

          //here your code

        return returnData;
    }

    @Override
    protected void onPostExecute(String returnedData) {
       //
   String[] parts = returnedData.split(" ");
   ArrayList<String> clientRawData = new ArrayList<String>();
   clientRawData.addAll(Arrays.asList(parts));

   //Time of last update from weather station.
   contentTitle = contentTitle + parts[29] + ":" + parts[30]; 

   Log.e("log_etag", "Content Title " + contentTitle);

   // The Intent to be used when the user clicks on the Notification View
   notificationIntent = new Intent(context, MainActivity.class);

   // The PendingIntent that wraps the underlying Intent
    mContentIntent = PendingIntent.getActivity(context, 0,
        notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    // Build the Notification
     Notification.Builder notificationBuilder = new Notification.Builder(
        context).setTicker(tickerText)
        .setSmallIcon(android.R.drawable.stat_sys_warning)
        .setAutoCancel(true).setContentTitle(contentTitle)
        .setContentText(contentText).setContentIntent(mContentIntent);


    // Get the NotificationManager
    NotificationManager mNotificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);

    // Pass the Notification to the NotificationManager:
    mNotificationManager.notify(MY_NOTIFICATION_ID,
        notificationBuilder.build());

    }


  }
}