Android Widget 小組件(一) 簡單實現

來源:互聯網
上載者:User

標籤:android widget

在螢幕上添加Widget:或長按螢幕空白處,或找到WidgetPreview App選擇。原生系統4.0以下使用長按方式,4.0及以上 開啟WIDGETS

建立Widget的一般步驟:
在menifest中

<receiver android:name="com.stone.ui.TimerWidgetProvider">             <intent-filter>                 <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>                 <!-- 自訂action -->                 <action android:name="com.stone.action.start"/>             </intent-filter>             <meta-data android:name="android.appwidget.provider"                 android:resource="@xml/timer_widget_provider"/>                 <!--  android:resource="" 定義了Widget的資訊使用timer_widget_provider.xml描述 --></receiver>

Widget描述檔案:timer_widget_provider.xml
<?xml version="1.0" encoding="utf-8"?><appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"    android:minWidth="180dp"    android:minHeight="40dp"    android:updatePeriodMillis="5000"    android:previewImage="@drawable/ic_launcher"    android:initialLayout="@layout/timer_widget"    android:resizeMode="horizontal|vertical" ><!-- 計算size的公式: (70*n) -30  n為組件所需的大小(占幾格)   當前的就是  3X1minResizeWidth    minResizeHeight   能被調整的最小寬高,若大於minWidth minHeight 則忽略    label選擇組件時看到標籤    icon選擇組件時看到表徵圖    updatePeriodMillis更新時間間隔    previewImage選擇組件時 展示的映像  3.0以上使用    initialLayout布局檔案    resizeMode調整size模式    configure如果需要在啟動前先啟動一個Activity進行設定,在這裡給出Activity的完整類名    [email protected]/xx與集合組件一起使用,指定應該通過組件的host自動提前的視圖ID        集合組件:3.0後才有。view:ListView、GridView、StackView、AdapterViewFilpper --></appwidget-provider>

Widget使用的布局:timer_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="horizontal"    android:background="@drawable/widget_background" >    <TextView     android:id="@+id/counter"    android:layout_width="0dp"    android:layout_height="match_parent"    android:layout_weight="1"    android:gravity="center"    android:text="00:00"    android:singleLine="true"    android:textAppearance="?android:attr/textAppearance"/><ImageView    android:id="@+id/start_stop"    android:layout_width="0dp"    android:layout_height="match_parent"    android:layout_weight="1"    android:scaleType="center"    android:src="@android:drawable/ic_media_play"/></LinearLayout>

處理Widget相關事件的 AppWidgetProvider
package com.stone.ui;import java.util.Arrays;import com.stone.R;import com.stone.service.TimerWidgetService;import android.app.PendingIntent;import android.appwidget.AppWidgetHost;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.text.format.DateUtils;import android.widget.RemoteViews;/* * AppWidgetProvider 必須要接收android.appwidget.action.APPWIDGET_UPDATE 廣播 *  */public class TimerWidgetProvider extends AppWidgetProvider {@Override //更新組件時調用,在第1次添加組件時也會調用public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {super.onUpdate(context, appWidgetManager, appWidgetIds);System.out.println("onUpdate widget:" + Arrays.toString(appWidgetIds));/* * 構造pendingIntent發廣播,onReceive()根據收到的廣播,更新 */Intent intent = new Intent(context, TimerWidgetService.class);PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.timer_widget);rv.setOnClickPendingIntent(R.id.start_stop, pendingIntent);appWidgetManager.updateAppWidget(appWidgetIds, rv);}@Override//組件從host中刪除public void onDeleted(Context context, int[] appWidgetIds) {super.onDeleted(context, appWidgetIds);System.out.println("onDeleted widget");}@Override //第1次建立時調用,之後再建立不會調用public void onEnabled(Context context) {super.onEnabled(context);System.out.println("onEnabled widget");}@Override //當最後一個組件執行個體 被刪除時 調用  用於清除onEnabled執行的操作public void onDisabled(Context context) {super.onDisabled(context);System.out.println("onDisabled widget");}@Override //public void onReceive(Context context, Intent intent) {super.onReceive(context, intent);System.out.println("onReceive widget");/* * 接收 <action android:name="com.stone.action.start"/>           在其他組件或activity或service中發送這些廣播            */if (intent.getAction().equals("com.stone.action.start")) {long time = intent.getLongExtra("time", 0); updateWidget(context, time); System.out.println("receive com.stone.action.start");}}private void updateWidget(Context context, long time) {//RemoteViews處理異進程中的ViewRemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.timer_widget);System.out.println("time=" + time);rv.setTextViewText(R.id.counter, DateUtils.formatElapsedTime(time / 1000));AppWidgetManager am = AppWidgetManager.getInstance(context);int[] appWidgetIds = am.getAppWidgetIds(new ComponentName(context, TimerWidgetProvider.class));am.updateAppWidget(appWidgetIds, rv);//更新 所有執行個體}}

AppWidgetProvider中使用的TimerWidgetService

package com.stone.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class TimerWidgetService extends Service {@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {/* * do some thing *///發送廣播通知 widget 更新 狀態sendBroadcast(new Intent("com.stone.action.start").putExtra("time", System.currentTimeMillis()));return Service.START_STICKY;}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.