一、AppWidget介绍
1.要在手机生成AppWidget需的东西
(1)AppWidgetProviderInfo
a).resxmlexample_appwidget_info.xml
b)a中需要布局文件reslayoutexample_appwidget.xml来定义AppWidget的样式
(2)AppWidgetProvider
a)自定义一个类ExampleAppWidgetProvider继承AppWidgetProvider,根据需求重写onXXX()
b)AppWidgetProvider实质是一个BroadcastReciever,通过接收系统广播来操作AppWidget,所以需要在AndroidManifest.xml定义<receiver>及其<intent-filter>等
2.
二、代码
1.res/xml/example_appwidget_info.xml
1 <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" 2 android:minWidth="294dp" 3 android:minHeight="72dp" 4 android:updatePeriodMillis="86400000" 5 android:initialLayout="@layout/example_appwidget" 6 > 7 </appwidget-provider>
2.res/layout/example_appwidget.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/widgetTextId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="firstWidgetText" android:background="#000000" /> </LinearLayout>
3.ExampleAppWidgetProvider.java
1 package mars.appwidget01; 2 3 import android.appwidget.AppWidgetManager; 4 import android.appwidget.AppWidgetProvider; 5 import android.content.Context; 6 7 public class ExampleAppWidgetProvider extends AppWidgetProvider{ 8 9 @Override 10 public void onUpdate(Context context, AppWidgetManager appWidgetManager, 11 int[] appWidgetIds) { 12 System.out.println("onupdate"); 13 super.onUpdate(context, appWidgetManager, appWidgetIds); 14 } 15 16 @Override 17 public void onDeleted(Context context, int[] appWidgetIds) { 18 System.out.println("onDeleted"); 19 super.onDeleted(context, appWidgetIds); 20 } 21 22 @Override 23 public void onDisabled(Context context) { 24 System.out.println("onDisabled"); 25 super.onDisabled(context); 26 } 27 28 @Override 29 public void onEnabled(Context context) { 30 System.out.println("onEnabled"); 31 super.onEnabled(context); 32 } 33 34 }
4.AndroidManifest.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="mars.appwidget01" android:versionCode="1" android:versionName="1.0"> 4 <application android:icon="@drawable/icon" android:label="@string/app_name"> 5 <activity android:name=".MainActivity" android:label="@string/app_name"> 6 <intent-filter> 7 <action android:name="android.intent.action.MAIN" /> 8 <category android:name="android.intent.category.LAUNCHER" /> 9 </intent-filter> 10 </activity> 11 <receiver android:name="ExampleAppWidgetProvider"> 12 <intent-filter> 13 <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> 14 </intent-filter> 15 <meta-data android:name="android.appwidget.provider" 16 android:resource="@xml/example_appwidget_info" /> 17 </receiver> 18 </application> 19 <uses-sdk android:minSdkVersion="7" /> 20 21 </manifest>