編輯:關於 Android 程式設計
桌面小工具(App Widget)和普通 Activity 差別很大:它的畫面由 RemoteViews 描述,必須透過 AppWidgetProvider 接收更新廣播,而且更新頻率受系統限制。以下用一個每秒刷新時間的時鐘,把整個流程走一遍。
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.widget"
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=".TimeWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/timewidget_info" />
</receiver>
<service android:name=".TimerService"></service>
</application>
</manifest>
<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="https://schemas.android.com/apk/res/android"
android:initialLayout="@layout/time_appwidget"
android:minHeight="40dp"
android:minWidth="40dp"
android:updatePeriodMillis="0" />
這裡把 updatePeriodMillis 設為 0,代表不依賴系統的定時更新機制,改由自己的 Service 控制節奏——因為系統對這個值有下限限制(最短約 30 分鐘),拿來做時鐘完全不可行。
<?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"
android:background="@drawable/rectangle" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="current time" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 設置弧度 -->
<corners android:radius="9dp" />
<gradient
android:angle="270"
android:startColor="#B3F0FF"
android:endColor="#5EADF4" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<stroke
android:width="6dp"
android:dashWidth="10dp"
android:dashGap="1dp"
android:color="#0000FF" />
</shape>
package com.example.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
public class TimeWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
// 當某個 Widget 被刪除時呼叫
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
// 第一次往桌面添加同類型 Widget 時呼叫,之後再加不會觸發
public void onEnabled(Context context) {
context.startService(new Intent(context, TimerService.class));
}
// 從桌面刪除最後一個同類型 Widget 時呼叫
public void onDisabled(Context context) {
context.stopService(new Intent(context, TimerService.class));
}
}
把 Service 的啟動與停止綁在 onEnabled() / onDisabled() 上,是這裡最關鍵的設計:桌面上還有這個時鐘,Service 就活著;最後一個被移除,Service 自動收工,不會留下無用的背景程序。
package com.example.widget;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;
public class TimerService extends Service {
private Timer timer;
@Override
public void onCreate() {
super.onCreate();
timer = new Timer();
timer.schedule(new MyTimerTask(), 0, 1000);
}
private final class MyTimerTask extends TimerTask {
@SuppressLint("SimpleDateFormat")
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
String time = sdf.format(new Date());
// 取得 Widget 管理器
AppWidgetManager widgetManager =
AppWidgetManager.getInstance(getApplicationContext());
// 對應目前 Widget 的遠程視圖
RemoteViews remoteView =
new RemoteViews(getPackageName(), R.layout.time_appwidget);
remoteView.setTextViewText(R.id.textView, time);
// 點擊 Widget 時的行為:
// remoteView.setOnClickPendingIntent(viewId, pendingIntent)
ComponentName componentName = new ComponentName(
getApplicationContext(), TimeWidgetProvider.class);
widgetManager.updateAppWidget(componentName, remoteView);
}
}
@Override
public void onDestroy() {
timer.cancel();
timer = null;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
RemoteViews,只能使用支援的版面與控制項,不能直接抓 View 來操作。AppWidgetManager.updateAppWidget() 送出,並以 ComponentName 指定目標 Provider。onDestroy() 中 cancel(),否則會造成資源洩漏。PendingIntent 綁到 setOnClickPendingIntent()。
Android 數據存儲全解:SharedPreferences、內部存儲與 SDCard 讀寫
一、Android 的五種存儲方式 Android 官方把 Data Storage 分成 Storage Options 五類,這是理解後續所有存儲 API 的地基:
Android Service 全面解析:分類、生命週期與使用方式
一、Service 的分類 依執行位置:本地服務與遠程服務 本地服務(Local)依附在主進程上,因此不必 IPC、也不用寫 AIDL,bindService 相對簡單,
Android 圖片上傳功能實作:相機、相簿與多圖選擇器
最近在開發使用者意見回饋功能,需要讓使用者輸入文字或提交圖片,效果大致類似微信朋友圈那樣的多圖選擇器。 一開始我找了一個用 universal-image-loader
徹底搞懂 Android layout_weight 的分配規則
layout_weight 是使用 LinearLayout 時幾乎必備的屬性,但它的行為有個反直覺之處,讓不少人第一次用時都栽了跟頭。搞懂背後的計算方式,之後排版會順手