0

这是我的 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;



}

问题是我的代码似乎死了

响应 = client.execute(get);

根据 LogCat 告诉我的内容。它在该行和 data=connect(); 处指出了标签“System.err”。

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

编辑:

这是日志猫。

06-27 21:30:38.058: W/System.err(28060): 在 com.example.psi.MyWidgetProvider.connect(MyWidgetProvider.java:284) 06-27 21:30:38.058: W/System.err( 28060): 在 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)

4

1 回答 1

0

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

是进入 StrictMode 线程策略,

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

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

于 2013-06-27T13:43:42.427 回答