标签:
widget.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="时间显示" /> </LinearLayout>
widgetconfig.xml
<?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="100dp" android:minHeight="40dp" android:initialLayout="@layout/widget" android:updatePeriodMillis="5000" > </appwidget-provider>
android:updatePerioMillis 使用系统定时更新服务,单位毫秒。
这里需要说明android:updatePerioMillis的问题,系统为了省电,默认是30分钟更新一次,如果你设置的值比30分钟小,系统也是30分钟才会更新一次
TimerService.java
public class TimerService extends Service{ private Timer timer; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { updateView(); } }, 1, 1000); } private void updateView(){ String time = sdf.format(new Date()); RemoteViews rv = new RemoteViews(getPackageName(), R.layout.widget); rv.setTextViewText(R.id.tv, time); AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext()); ComponentName cn = new ComponentName(getApplicationContext(), WidgetProvider.class); manager.updateAppWidget(cn, rv); } @Override public void onDestroy() { super.onDestroy(); timer = null;//widget销毁 } }
widgetProvider.java
public class WidgetProvider extends AppWidgetProvider { @Override public void onDeleted(Context context, int[] appWidgetIds) { super.onDeleted(context, appWidgetIds); } @Override public void onEnabled(Context context) { super.onEnabled(context); context.startService(new Intent(context,TimerService.class));//开启服务 } @Override public void onDisabled(Context context) { super.onDisabled(context); context.stopService(new Intent(context,TimerService.class));//停止服务 } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); } }
AndroidManifest.xml添加关键代码
<service android:name="com.anlen.call.service.TimerService" > </service> <receiver android:name="com.anlen.call.ui.widget.WidgetProvider" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" > </action> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/widgetconfig" > </meta-data> </receiver>
标签:
原文地址:http://my.oschina.net/anlen/blog/531841