下載、備份這類耗時任務,最適合把進度搬到通知欄——使用者不必停在你的 App 裡,也能看到跑到哪裡了。這個 DEMO 對 Android 初學者是很好的練習題,因為它同時用到 Notification、RemoteViews、PendingIntent 與背景執行緒的溝通。
運作方式很直觀:點擊顯示按鈕,通知欄會出現一條帶圖示與進度條的提示,進度由背景執行緒每 1000 毫秒推進一次;點擊取消按鈕則立即移除通知並中止執行緒。
通知欄的內容不能塞入一般 View,必須用 RemoteViews 指向一個 layout,再透過 setProgressBar 操作其中的元件。更新時要重新呼叫 NotificationManager.notify 並沿用同一個 id,通知才會原地刷新而非堆疊出新的一條。另外,Activity 進入 onPause 時務必中斷執行緒並取消通知,否則離開畫面後進度仍會繼續跑。
FTP 位址:ftp://www.linuxidc.com
帳號:www.linuxidc.com
密碼:www.muu.cc
目錄:2011年LinuxIDC.com\10月\10月\Android帶進度條的通知欄源碼
下載方法見 https://www.linuxidc.net/thread-1187-1-1.html
package com.hemowolf;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RemoteViews;
public class main extends Activity implements OnClickListener {
@Override
protected void onPause() {
super.onPause();
_thread.interrupt();
nm.cancel(NF_ID);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnShow).setOnClickListener(this);
findViewById(R.id.btnCancel).setOnClickListener(this);
nf = new Notification(R.drawable.icon, "帶進度條的提醒", System.currentTimeMillis());
nf.icon = R.drawable.icon;
nf.contentView = new RemoteViews(this.getPackageName(), R.layout.notification);
nf.contentView.setProgressBar(R.id.ProgressBar01, 100, 0, false);
nf.contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, remoteview.class), 0);
nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnShow:
nm.notify(NF_ID, nf);
_thread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
_handler.sendMessage(Message.obtain());
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
});
_thread.start();
break;
case R.id.btnCancel:
_thread.interrupt();
nm.cancel(NF_ID);
break;
}
}
private Handler _handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
_progress += 10;
if (_progress >= 100) _progress = 0;
nf.contentView.setProgressBar(R.id.ProgressBar01, 100, _progress, false);
nm.notify(NF_ID, nf);
}
};
private final int NF_ID = 1111;
private Notification nf;
private NotificationManager nm;
private int _progress = 0;
private Thread _thread;
}
若要移植到較新的 Android 版本,記得 Notification 的 builder 與 channel 機制已全面改版,本範例的寫法僅適用於早期 API。