0

У меня проблема с закрытием моей виджеты. Я читал, что мне, возможно, нужно сделать расширение AsyncTask, но не может на всю жизнь выяснить, как это сделать с AppWidgetProvider. Я начал использовать учебник, в котором использовались устаревшие функции, а затем понял, что мне нужно использовать HttpURLConnection, теперь он закроется.Android Widget HttpURLConnection Forceclosing

Этот виджет предназначен только для меня, чтобы следить за температурой котла на работе, и я отнюдь не разработчик Android. Любая помощь серьезно оценена.

public class BoilerTemp extends AppWidgetProvider { 

    String name; 

    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
     // There may be multiple widgets active, so update all of them 
     final int N = appWidgetIds.length; 
     for (int i = 0; i < N; i++) { 
      updateAppWidget(context, appWidgetManager, appWidgetIds[i]); 
     } 
     Timer timer = new Timer(); 
     timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 10000); 
     select(); 
    } 

    public void select() 
    { 
     try{ 
     URL url = new URL("http://www.someurl.com/temp/select.php"); 
     HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
     connection.setRequestProperty("User-Agent", ""); 
     connection.setRequestMethod("POST"); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream inputStream = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
      while ((line = rd.readLine()) != null) { 
       name = line; 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private class MyTime extends TimerTask { 
     RemoteViews remoteViews; 
     AppWidgetManager appWidgetManager; 
     ComponentName thisWidget; 
     DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()); 

     public MyTime(Context context, AppWidgetManager appWidgetManager) { 
      this.appWidgetManager = appWidgetManager; 
      remoteViews = new RemoteViews(context.getPackageName(), R.layout.boiler_temp); 
      thisWidget = new ComponentName(context, BoilerTemp.class); 
     } 
     @Override 
     public void run() { 
      remoteViews.setTextViewText(R.id.appwidget_text, "TEMP = " + name + " - " + format.format(new Date())); 
      appWidgetManager.updateAppWidget(thisWidget, remoteViews); 
     } 

    } 


    @Override 
    public void onEnabled(Context context) { 
     // Enter relevant functionality for when the first widget is created 
    } 

    @Override 
    public void onDisabled(Context context) { 
     // Enter relevant functionality for when the last widget is disabled 
    } 

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, 
           int appWidgetId) { 

     CharSequence widgetText = context.getString(R.string.appwidget_text); 
     // Construct the RemoteViews object 
     RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.boiler_temp); 
     views.setTextViewText(R.id.appwidget_text, widgetText); 

     // Instruct the widget manager to update the widget 
     appWidgetManager.updateAppWidget(appWidgetId, views); 
    } 
} 

обновление Я нашел этот код сделал приложение работает, но в то же время серьезно неодобрительно.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

Любые лучшие решения?

+1

Использование LogCat для изучения трассировки стека Java, связанный с грохотом: https://stackoverflow.com/questions/23353173/К сожалению, myapp-has-stop-how-can-i-solve-this – CommonsWare

+0

К сожалению, LogCat пуст. Я использую Android Stuido – Jptalon

+0

Наконец-то я получил что-то в окне LogCat. java.lang.RuntimeException: невозможно запустить приемник – Jptalon

ответ

0

Попробуйте этот код (он анализирует XML из URL-адреса).

Призвание

parser = new XMLParser(); 
parser.execute(context); 

XML Parser класс

public class XMLParser extends AsyncTask { 

    private Exception exception; 

    @Override 
    // Parse XML 
    protected Object doInBackground(Object[] objects) { 
     Context context = (Context) objects[0]; 

     HttpURLConnection connection; 
     InputStream inputStream; 
     try { 
      URL input = new URL("http://...."); 
      connection = (HttpURLConnection) input.openConnection(); 
     } catch (IOException e) { 
      exception = e; 
      ... 
      return context; 
     } finally { 
      if (connection != null) { 
       connection.disconnect(); 
      } 
     } 

     try { 

      XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
      XmlPullParser parser = factory.newPullParser(); 

      connection.setRequestMethod("GET"); 
      connection.setRequestProperty("Accept", "application/xml"); 
      inputStream = connection.getInputStream(); 
      parser.setInput(inputStream, "UTF-8"); 
      ... 
    } 

    // Parsing done 
    protected void onPostExecute(Object val) { 
     if (exception != null) { 
      sentIntent((Context) val, false); 
      exception.printStackTrace(); 
     } else { 
      if (val != null) { 
       sentIntent((Context) val, true); 
      } 
     } 
    } 

    // Sent intent when parsing done 
    private void sentIntent(Context context, final boolean extra) { 
     Intent intent = new Intent(context, BoilerTemp.class); 
     intent.setAction(Constants.ACTION_XML_PARSED); 
     context.sendBroadcast(intent); 
    } 
} 

}

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