30 April 2010
android 2.0 以上 app_widget不支援每秒update一次

最小時間是三十分鐘..

這邊利用thread去做到每秒執行很多次...

首先我們要先建立一個widget的設定檔

xml/analog_appwidget.xml


<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"  
  android:minWidth="146dip"  
  android:minHeight="146dip"  
  android:updatePeriodMillis="1000"  
  android:initialLayout="@layout/analog_appwidget" >  
</appwidget-provider>  


以及widget的樣式



layout/analog_appwidget.xml



<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

 <TextView
  android:id="@+id/TextView01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="efefefefefef">
 </TextView>
</LinearLayout>



接著在AndroidMainfest.xml貼入下段



 
<receiver android:name="AnalogAppWidgetProvider" >  
 <intent-filter>  
   <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />  
 </intent-filter>  
 <meta-data android:name="android.appwidget.provider"   
            android:resource="@xml/analog_appwidget" />  
</receiver>

接著開始寫CODE搂~


AnalogAppWidgetProvider.java


   
//import省略
public class AnalogAppWidgetProvider extends AppWidgetProvider {

Context context_main ;
AppWidgetManager app_manager;
int []appWidgetId;

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

app_manager = appWidgetManager;
context_main = context;
appWidgetId = appWidgetIds;

   Thread thread = new Thread(new update_thread());
   thread.start();

}

public class update_thread implements Runnable{
@Override
public void run() {
int i = 0;
while(true && i++ <100){
RemoteViews views =
 new RemoteViews(context_main.getPackageName(), R.layout.analog_appwidget);
views.setTextViewText(R.id.TextView01, String.valueOf(Math.random()) );

app_manager.updateAppWidget(appWidgetId, views);
}
}
}

}











照著上列步驟即可實現...



如果需要是以每秒去update在自行更改


此範例只是個小sample


















blog comments powered by Disqus