2015-01-18 6 views
0

Я пробовал весь день, но я не могу понять, как это понять. Я пытаюсь вернуть строку из AsyncTask в BroadcastReceiver, но я не уверен, как это сделать правильно (новое на Java). У меня есть приложение, которое обращается к Интернету и читает текстовый файл, и этот текстовый файл является длинной строкой. Я делит строку на массив и использую его содержимое таким образом. В BroadcastReceiver я хочу транслировать (обновлять) температуру от метеостанции каждые 10-60 минут в зависимости от того, что пользователь настраивает на панели уведомлений.Возврат строки из AsyncTask в BroadcastReceiver

Должен ли я использовать Thread вместо AsyncTask?
Ошибки я получаю следующую строку:

выход String = новые GetWeatherValues ​​() выполнение (weburi);.

Я также попытался следующий код, который закомментирована:

// GetWeatherValues ​​clientraw = новые 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; 
    } 
} 
} 
+0

не запускать асинхронной задачи в радиовещательного приемника. После того, как метод onReceive завершает работу, экземпляр приемника неприменим. Используйте приемник для запуска «IntentService» или «Service», который будет выполнять фактическую работу. –

+0

Google "EventBus". Вы можете использовать его для публикации данных от служб к действиям или между чем угодно. –

+0

Как насчет запуска нити? Это тоже плохая идея? – Dino

ответ

1

, что вы можете сделать, это переопределить onPostExecute() в асинхронным Задача взглянуть на эту ссылку для How to use AsyncTask correctly in Android

onPostExecute() позволяют обрабатывать ваши вещи на UI тему.

и здесь вы можете получить доступ к String (Строка returnData)

и вы также можете возвратить значение из асинхронной-задачи для этого есть взгляд на этой ссылке 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()); 

    } 


    } 
} 
+0

А, я вижу, вы перевели код на onPostExecute(). Согласно одной из ссылок, которые вы мне указали, говорится, что я должен делать обновления интерфейса в этом методе. Как получить контекст в этом методе? – Dino

+0

да .... твой правый ...... –

+0

, если этот ответ удовлетворяет вашей проблеме, а затем любезно принять его. –

Смежные вопросы