我的小部件似乎不想从HttpResponse执行HttpGet

时间:2013-06-27 13:16:32

标签: android httpresponse android-appwidget http-get onupdate

这是我的onUpdate代码。

    ComponentName thisWidget = new ComponentName(context,
            MyWidgetProvider.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
      final int N = appWidgetIds.length;



  for ( int ii = 0; ii < N ; ii++)
  {
  RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
            R.layout.widget_layout);
  Toast.makeText(context, "Loading", Toast.LENGTH_SHORT).show();
    remoteViews.setTextViewText(R.id.update, "Loading2");


 try {
    data = connect();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


    now = Calendar.getInstance();
    timeHour = now.get(Calendar.HOUR_OF_DAY);

    remoteViews.setTextViewText(R.id.update, "The latest PSI reading is " + data);



Intent intent = new Intent(context, MyWidgetProvider.class);

intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);

appWidgetManager.updateAppWidget(allWidgetIds, remoteViews);

  }

}

这是connect();

的方法
public String connect() throws IOException
{       String temp = "WAD";

    try {
    HttpClient client = new DefaultHttpClient();

    HttpGet get = new HttpGet("http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours");

    HttpResponse response;


        response = client.execute(get);
        HttpEntity entity = response.getEntity();

        InputStream in = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null){

            sb.append(line+"\n");


        }
        in.close();
        temp = sb.toString();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return temp;



}

事情是我的代码似乎死了

response = client.execute(get);

根据LogCat告诉我的内容。它指出了那一行的标签“System.err”,以及data = connect();

connect()方法在其他应用程序上运行良好,而不是小部件,所以我不知道我做错了什么。

编辑:

这是logcat。

06-27 21:30:38.058:W / System.err(28060):at com.example.psi.MyWidgetProvider.connect(MyWidgetProvider.java:284) 06-27 21:30:38.058:W / System.err(28060):at com.example.psi.MyWidgetProvider.onUpdate(MyWidgetProvider.java:71) 06-27 21:30:38.058:W / System.err(28060):在android.appwidget.AppWidgetProvider.onReceive(AppWidgetProvider.java:66)

1 个答案:

答案 0 :(得分:0)

编辑:我找到了解决方案,

进入StrictMode threadpolicy,

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

我知道这不是最好的方法,但我正在做一个概念验证而不是试图使这个应用程序流畅。