<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.widget_sample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name=".MainActivity" android:label="WIDGET_SAMPLE"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/my_widget" /> </receiver> <service android:name="MainActivity$MyService" > <intent-filter> <action android:name="Widget.Button.Click"></action> </intent-filter> </service> </application> </manifest>
Package com. example. widget_sample; import java. util. timer; import android. app. pendingIntent; import android. app. service; import android. appwidget. appWidgetManager; import android. appwidget. appWidgetProvider; import android. content. componentName; import android. content. context; import android. content. intent; import android. OS. IBinder; import android. util. log; import android. widget. remoteViews; public class Main Activity extends AppWidgetProvider {public Context context; static int num = 100; static String tag_action = "Widget. button. click "; public void onUpdate (Context con, AppWidgetManager appWidgetManager, int [] appWidgetIds) {context = con; Intent intent = new Intent (context, MyService. class); context. startService (intent);} // MyService Service program public static class MyService extends Service {public void onStart (Int Ent intent, int startId) {ComponentName thisWidget = new ComponentName (this, MainActivity. class); AppWidgetManager manager = AppWidgetManager. getInstance (this); RemoteViews remoteViews = new RemoteViews (getPackageName (), R. layout. activity_main); // if (intent. getAction ()! = Null) {if (intent. getAction (). equals (tag_action) {num -- ;}} remoteViews. setTextViewText (R. id. textView1, String. valueOf (num); // defines an Intent to send the ActionIntent prevInten = new Intent (); prevInten. setAction (tag_action); // use Intent to instantiate a PendingIntentPendingIntent Pprevintent = PendingIntent. getService (this, 0, prevInten, 0); // set the Button event remoteViews for the Button on the RemoteView. setOnClickPendingIntent (R. id. button1, Pprevintent); manager. updateAppWidget (thisWidget, remoteViews);} @ Overridepublic IBinder onBind (Intent arg0) {// TODO Auto-generated method stubreturn null ;}}}