Return 来自 BroadcastReceiver 中 AsyncTask 的字符串

Return String from AsyncTask in BroadcastReceiver

我已经尝试了一整天,但我似乎无法弄清楚。我正在尝试 return 来自 BroadcastReceiver 中 AsyncTask 的字符串,但我不确定如何正确地执行它(Java 中的新内容)。我有一个访问互联网并读取文本文件的应用程序,这个文本文件是一个长字符串。我将字符串分隔成一个数组并以这种方式使用它的内容。在 BroadcastReceiver 中,我想每 10-60 分钟从气象站广播(更新)一次温度,具体取决于用户在通知栏上的设置。

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

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

我也尝试了下面被注释掉的代码:

// GetWeatherValues clientraw = new GetWeatherValues();

// clientraw.doInBackground(weburi);

下面是我的Class,求助,我找了很多都没有结果

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

你可以做的是在异步任务中覆盖 onPostExecute() 看看这个 link for How to use AsyncTask correctly in Android

onPostExecute() 允许在 UI 线程上处理您的事情。

在这里您可以访问您的字符串(字符串 return数据)

你也可以 return 来自异步任务的值,看看这个 link 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());

    }


  }
}