AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="wandroide.blogspot.com" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name=".MyAppWidget" android:label="@string/app_name"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/myappwidget_provider" /> </receiver> </application> <uses-sdk android:minSdkVersion="7" /> </manifest>main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/widget_textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World!</string> <string name="app_name">MyAppWidget</string> </resources>myappwidget_provider.xml
<?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="146dip" android:minHeight="72dip" android:updatePeriodMillis="10000" android:initialLayout="@layout/main"> </appwidget-provider>MyAppWidget.java
package wandroide.blogspot.com; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import android.content.ComponentName; import android.content.Context; import android.appwidget.AppWidgetProvider; import android.appwidget.AppWidgetManager; import android.widget.RemoteViews; public class MyAppWidget extends AppWidgetProvider { //====顯示widget @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Timer timer = new Timer(); timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000); } private class MyTime extends TimerTask { RemoteViews remoteViews; AppWidgetManager appWidgetManager; ComponentName thisWidget; DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()); public MyTime(Context context, AppWidgetManager appWidgetManager) { this.appWidgetManager = appWidgetManager; remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); thisWidget = new ComponentName(context, MyAppWidget.class); } @Override public void run() { remoteViews.setTextViewText(R.id.widget_textview, "Time = " + format.format(new Date())); appWidgetManager.updateAppWidget(thisWidget, remoteViews); } } }
作者已經移除這則留言。
回覆刪除