如何更新Android App Widget?

时间:2012-07-31 05:06:57

标签: android android-widget

我是android编程的新手。在我的android小部件中,我喜欢从名为get details的方法更新数据。我尝试使用下面的代码,但它也无法正常工作,所以请指出我的代码中有任何错误

Android Manifest xml

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

  <uses-sdk android:minSdkVersion="10" />
  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    <receiver android:name=".MyW" android:label="WatchWidget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="android.appwidget.action.APPWIDGET_ENABLED"/>                
        </intent-filter>
        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_provider" />
    </receiver>
</application>
</manifest>

窗口小部件源

public class MyW extends AppWidgetProvider {
public String deviceinfo = null;
public Context mContext = null;
public int asu = 0;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    mContext = context;
    RemoteViews remoteViews;
    ComponentName watchWidget;
    remoteViews = new RemoteViews( context.getPackageName(), R.layout.main );
    watchWidget = new ComponentName( context, MyW.class );
    remoteViews.setTextViewText( R.id.widget_textview, "OK -> " + deviceinfo);
    appWidgetManager.updateAppWidget( watchWidget, remoteViews );
}

@Override
public void onReceive(Context context, Intent intent) {
    mContext = context;

    RemoteViews remoteViews;
    ComponentName watchWidget;
    remoteViews = new RemoteViews( context.getPackageName(), R.layout.main );
    watchWidget = new ComponentName( context, MyW.class );
    remoteViews.setTextViewText( R.id.widget_textview, "OK => " + deviceinfo);
    AppWidgetManager.getInstance(context).updateAppWidget( watchWidget, remoteViews );
}

@Override
public void onEnabled(Context context) {
    mContext = context;
    getDetails();
}

public void getDetails(){
       deviceinfo = "Hi friends";

       Intent i = new Intent(mContext, MyW.class);
       mContext.sendBroadcast(i);
}   
 }

感谢

0 个答案:

没有答案