doukongpao0903 2014-06-11 14:37
浏览 92

从php文件更新android(homescreen)小部件

I want to make a android widget that it will update from a php file. i found a lot of examples about widgets and a lot of examples of how to retrieve data from php to an activity but i didn't manage to do it. i need something like this example (http://www.vogella.com/tutorials/AndroidWidgets/article.html) but instead of a random number i need to take the number from my php file..

php file it output a single number that i need to include in my widget (http://www.angryboards.com/data/larnaca/test.php)

this the WidgetProvider class, but when i am trying to call the AsyncTask in onUpdate() it crashes.

public class MyWidgetProvider extends AppWidgetProvider {

 private TextView textView;


  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager,
      int[] appWidgetIds) {

      //call AsyncTask
       String serverURL = "http://www.angryboards.com/data/larnaca/test.php";
         new async().execute(serverURL);
         String txt = textView.getText().toString();


    // Get all ids
    ComponentName thisWidget = new ComponentName(context,
        MyWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {






      RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
          R.layout.widget_layout);

      // Set the text
      remoteViews.setTextViewText(R.id.update, txt);

      // Register an onClickListener
      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(widgetId, remoteViews);
    }
  }

 private class async extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();


          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);




    }
  }

} 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tasos.widgettest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"

     />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.tasos.widgettest.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

 <receiver
   android:icon="@drawable/logo"
   android:label="Example Widget"
   android:name="MyWidgetProvider" >
   <intent-filter >
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
   </intent-filter>

   <meta-data
      android:name="android.appwidget.provider"
      android:resource="@xml/widget_info" />
</receiver> 

</application>
<uses-permission android:name="android.permission.INTERNET" />

</manifest>

widget_info.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider 
  xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget_layout"
android:minHeight="72dp"
android:minWidth="300dp"
android:updatePeriodMillis="3000" >

</appwidget-provider> 

and in layout i have a textview (android:id="@+id/update") Thanks

  • 写回答

1条回答 默认 最新

  • dongyuan9149 2014-06-18 00:28
    关注

    Done! i did a service that contains an AsyncTask and i call the service from appwigdetprovider.

    My UpdateWidgetService.java

    public class UpdateWidgetService extends Service {
    
    public String string;
    public String inputLine;
    public StringBuilder txt;
    public BufferedReader in;
    public URL url;
    
    
    
    @Override
    public void onStart(Intent intent, int startId) {
    
    
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
    int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
    
    for (int widgetId : allWidgetIds) {
    
    RemoteViews remoteViews = new     RemoteViews(this.getApplicationContext().getPackageName(),R.layout.widget_layout);
    Intent clickIntent = new Intent(this.getApplicationContext(),MyWidgetProvider.class);
    clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext() , 0,     clickIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    
    
    //refresh tapping the screen
    remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
    new DownloadTask().execute();
    
    
    appWidgetManager.updateAppWidget(widgetId, remoteViews);
    }
    stopSelf();
    
    super.onStart(intent, startId);
    }
    
    @Override
    public IBinder onBind(Intent intent) {
    return null;
    }
    
    public class DownloadTask extends AsyncTask<String, Void, String> {
    
    @Override
    protected String doInBackground(String... arg0) {
    
    try {
    url = new URL("http://www.angryboards.com/data/larnaca/latest_wind_value.php");
    in = new BufferedReader(new InputStreamReader(url.openStream()));
    inputLine = null;
    txt = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
    string = in.readLine();
    txt.append(inputLine);
    txt.append('
    ');
    
    
    }
    in.close();
    
    
    } catch (MalformedURLException e) {
    
    e.printStackTrace();
    } catch (IOException e) {
    
    e.printStackTrace();
    }
    return null;
    
    
    }
    
    @Override
    protected void onPostExecute(String result) {
    
    AppWidgetManager widgetManager = AppWidgetManager.getInstance(getApplication());
    //get widget ids for widgets created
    ComponentName widget = new ComponentName(getApplication(), MyWidgetProvider.class);
    int[] widgetIds = widgetManager.getAppWidgetIds(widget);
    //update text
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget_layout);
    remoteViews.setTextViewText(R.id.update, txt);
    //refresh widget to show text
    widgetManager.updateAppWidget(widgetIds, remoteViews); 
    
    
    }
    }
    
    
    }
    

    MyWidgetProvider.java

    public class MyWidgetProvider extends AppWidgetProvider {
    
      private static final String LOG = "com.tasos.widgettest";
    
    
      @Override
      public void onUpdate(Context context, AppWidgetManager appWidgetManager,
      int[] appWidgetIds) {
    
    Log.w(LOG, "onUpdate method called");
    // Get all ids
    ComponentName thisWidget = new ComponentName(context,
        MyWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    
    // Build the intent to call the service
    Intent intent = new Intent(context.getApplicationContext(),
        UpdateWidgetService.class);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
    
    // Update the widgets via the service
    context.startService(intent);
    
    
    
    
      }
    
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?