編輯:關於 Android 程式設計
繼 AppWidget 基礎篇之後,這次做一個「進階版」的小練習來驗收學習成果——一個點一下就擲骰子的桌面 Widget。
先看成品的樣子:



提醒一下,drawable 資料夾裡要先放進六張骰子點數圖,我是從網路上找的素材。
在 res 目錄下新增一個名為 xml 的資料夾(名字可自訂),並在其中建立 appwidget_info.xml,用來向系統宣告這個元件的基本資訊。
<appwidget-provider xmlns:android="https://schemas.android.com/apk/res/android"
android:minHeight="72dp"
android:minWidth="294dp"
android:updatePeriodMillis="86400000"
android:initialLayout="@layout/app_widget_layout" >
</appwidget-provider>
app_widget_layout.xml,一個 ImageView 顯示骰子、一個 Button 觸發擲骰:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageview_widget"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<Button
android:id="@+id/button_widget"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="搖一搖"
android:textColor="#6663c6" />
</LinearLayout>
package com.summer.mywidget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
public class WidgetProvider extends AppWidgetProvider {
private static final String MY_UPDATE_ACTION = "com.summer.APP_WIDGET_ACTION";
/* 隨機取得一張骰子圖的資源 id */
private static int getRandomPicture() {
int[] pictureArray = new int[]{R.drawable.dice_1, R.drawable.dice_2, R.drawable.dice_3,
R.drawable.dice_4, R.drawable.dice_5, R.drawable.dice_6};
int RandomNumber = (int) ((Math.random() * 100) % 6);
return pictureArray[RandomNumber];
}
/* 接收 action,用分支區分自訂 action 與系統 action */
@Override
public void onReceive(Context context, Intent intent) {
String RESPONSEACTION = intent.getAction();
Log.i("Summer", "------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + RESPONSEACTION);
if (MY_UPDATE_ACTION.equals(RESPONSEACTION)) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget_layout);
remoteViews.setImageViewResource(R.id.imageview_widget, getRandomPicture());
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, WidgetProvider.class);
appWidgetManager.updateAppWidget(componentName, remoteViews);
} else {
super.onReceive(context, intent);
}
}
/* 用迴圈處理桌面上放了多個相同 Widget 的情況 */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int i = 0; i < appWidgetIds.length; i++) {
Intent intent = new Intent();
intent.setAction(MY_UPDATE_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, -1, intent, 0);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget_layout);
remoteViews.setOnClickPendingIntent(R.id.button_widget, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
System.out.println("my app widget ----------------------------->>>>>>>onDeleted");
}
@Override
public void onEnabled(Context context) {
System.out.println("my app widget ----------------------------->>>>>>>onEnabled");
super.onEnabled(context);
}
@Override
public void onDisabled(Context context) {
System.out.println("my app widget ----------------------------->>>>>>>onDisabled");
super.onDisabled(context);
}
}
這裡有兩個重點:getRandomPicture() 負責隨機挑一張骰子圖;onReceive() 則攔下自訂的 broadcast action,判斷是「擲骰」還是系統訊息,前者就更新圖片、後者交給父類處理。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.summer.mywidget"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.summer.mywidget.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.summer.mywidget.WidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<intent-filter>
<action android:name="com.summer.APP_WIDGET_ACTION"></action>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info">
</meta-data>
</receiver>
</application>
</manifest>
注意這裡有兩個 intent-filter:一個接收系統的 APPWIDGET_UPDATE,另一個接收我們自訂的 action,兩者缺一不可。
跑起來之後,手動在桌面加入這個 Widget,你就擁有一顆自己的骰子了。
總結
這個小程式的邏輯並不複雜,但要寫順手,得對廣播機制與 PendingIntent 有基本認識。想再進一步的話,可以在每次擲骰時加上翻轉動畫,讓手感更好(RemoteViews 有提供相關方法)。程式碼難免還有不足之處,歡迎大家一起討論。
Android 手勢交互完整實作:GestureDetector 與 OnGestureListener 詳解
先看效果:一組可左右拋擲切換圖片的畫面。一、尚未拋擲二、向右拋擲一次三、再向右拋擲一次一、手勢交互的四個環節在 Android 中,每一次手勢交互都依下列順序發生:接觸觸
Android HTTP 網路請求實戰:GET、POST 與圖片下載完整範例
本文以 HttpURLConnection 為例,示範四種最常見的 HTTP 情境:直接抓取網頁內容、以 GET 帶參數、以 POST 送出表單,以及下載並顯示網路圖片。
Android 官方培訓譯文:打造你的第一個 App(Building Your First App)
Android App 的圖形用戶界面,是由一層又一層的 View 與 ViewGroup 對象搭建起來的。View 通常是各類 UI 控件(widget),比如按鈕或文
Android 鬧鐘定時功能實作筆記
最近參加一個比賽,作品是智能插座助手,需要用到定時觸發功能,於是順手做了一個類似鬧鐘的模塊,鬧鐘資訊用 Android 自帶的 SQLite 資料庫保存。 源碼位址:ht