简体   繁体   中英

Return String from AsyncTask in BroadcastReceiver

I have been trying all day, but I can't seem to figure it out. I am trying to return a string from AsyncTask in BroadcastReceiver but I am not sure how to do it correctly (new at Java). I have an app that accesses the internet and reads a text file and this text file is a long string. I delimit the string into an array and use it contents that way. In the BroadcastReceiver I want to broadcast (update) the temperature from the weather station every 10-60 minutes depending on what the user sets-up on the notification bar.

Should I use a Thread instead of AsyncTask?
The error I get is with the following line:

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

I also tried the following code that is commented out:

// GetWeatherValues clientraw = new GetWeatherValues();

// clientraw.doInBackground(weburi);

Below is my Class, please help, I have searched a lot and still no result.

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

what you can do is to override onPostExecute() in Async Task have a look at this link for How to use AsyncTask correctly in Android

onPostExecute() allow to handle your things on UI Thread.

and here you can access your String (String returnData)

and you can also return value from async-task for that have look at this link How to handle return value from AsyncTask but i will prefer for you not to that cos i will be a little bit complicated

a piece of code

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());

    }


  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM