Widget是一种BroadcastReceiver。
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name=".TimeWidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" />
</receiver>
<service android:name=".TimerService"></service>
</application>
public class TimeWidgetProvider extends AppWidgetProvider {
@Override
public void onDeleted(Context context, int[] appWidgetIds) {//当用户从桌面上删除widgets的时候就会调用此方法
}
@Override
public void onEnabled(Context context) {//第一次往桌面添加Widgets的时候才会被调用,往后再往桌面添加同类型Widgets的时候是不会被调用的
context.startService(new Intent(context, TimerService.class));
}
@Override
public void onDisabled(Context context) {//是在最后一个同类型Widgets实例被删除的时候调用
context.stopService(new Intent(context, TimerService.class));
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
}
}
public class TimerService extends Service {
private Timer timer;
@Override
public void onCreate() {
super.onCreate();
timer = new Timer();
timer.schedule(new TimeUpdateTask(), 0, 1000);
}
private final class TimeUpdateTask extends TimerTask{
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.time_appwidget);
remoteView.setTextViewText(R.id.textView, time);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 100,
new Intent(Intent.ACTION_CALL, Uri.parse("tel:133333333")), 0);
remoteView.setOnClickPendingIntent(R.id.textView, pendingIntent);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
appWidgetManager.updateAppWidget(
new ComponentName(getApplicationContext(), TimeWidgetProvider.class), remoteView);
}
}
@Override
public void onDestroy() {
timer.cancel();
timer = null;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
\res\layout\time_appwidget.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"
android:background="@drawable/rectangle"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/textView"
android:textColor="#FFFFFF"
android:textSize="14dp"
android:text="我是Widgets"
/>
</LinearLayout>
\res\xml\appwidget_info.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dp"
android:minHeight="72dp"
android:updatePeriodMillis="0"
android:initialLayout="@layout/time_appwidget"
/>