編輯:關於 Android 程式設計
本文示範一個可動態顯示、更新與移除的通知欄範例,重點在於當程式意外退出時,通知欄上的圖標不會殘留。
package com.notioni.test.notification;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class TestNotificationActivity extends Activity implements View.OnClickListener{
/** Called when the activity is first created. */
private boolean mStart = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int[] ids = {R.id.btnShow,R.id.btnUpdate,R.id.btnRemove};
for(int i = 0; i < ids.length; i++){
findViewById(ids[i]).setOnClickListener(this);
}
mStart = false;
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnShow://顯示通知欄
mStart = true;
sendMsgToService(NotificationService.KEY_COMMAND_SHOW,mStart);
break;
case R.id.btnUpdate://修改通知欄內容
sendMsgToService(NotificationService.KEY_COMMAND_UPDATE,!mStart);
break;
case R.id.btnRemove:
mStart = false;//移除通知欄
sendMsgToService(NotificationService.KEY_COMMAND_REMOVE,mStart);
break;
}
}
@Override
protected void onDestroy() {
mStart = false;
sendMsgToService(NotificationService.KEY_COMMAND_REMOVE,mStart);
super.onDestroy();
}
private void sendMsgToService(String cmd,boolean isStart){
Intent intent = new Intent(this,NotificationService.class);
intent.setAction(NotificationService.ACTION_NOTIFICATION_CONTROL);
intent.putExtra(NotificationService.COMMAND_KEY, cmd);
intent.putExtra(NotificationService.TIME_KEY, isStart);
startService(intent);
}
}
放三顆按鈕用來示範顯示、更新與移除:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnShow"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:text="@string/notification_show"
/>
<Button
android:id="@+id/btnUpdate"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:text="@string/notification_update"
/>
<Button
android:id="@+id/btnRemove"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:text="@string/notification_remove"
/>
</LinearLayout>
這是負責通知顯示、修改與移除的核心類別。
package com.notioni.test.notification;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;
public class NotificationService extends Service {
private static final String TAG = "NotificationService";
public static final String ACTION_NOTIFICATION_CONTROL = "action_notification_control";
public static final String COMMAND_KEY = "cmd_key";
public static final String KEY_COMMAND_SHOW = "show_notification";
public static final String KEY_COMMAND_UPDATE = "update_notification";
public static final String KEY_COMMAND_REMOVE = "remove_notification";
public static final String TIME_KEY = "time_key";
public static final int NOTIFICATIN_ID = 100;
private Notification mNotification;
private long mTime;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if(ACTION_NOTIFICATION_CONTROL.equals(action)){
String cmd = intent.getStringExtra(COMMAND_KEY);
boolean isStart = intent.getBooleanExtra(TIME_KEY, false);
Log.i(TAG, "[onStartCommand] action:"+action+",cmd:"+cmd+",isStart:"+isStart);
if(KEY_COMMAND_SHOW.equals(cmd)){
showNotification(isStart);
}else if(KEY_COMMAND_UPDATE.equals(cmd)){
updateNotification(isStart);
}else if(KEY_COMMAND_REMOVE.equals(cmd)){
removeNotification();
}
}else{
Log.e(TAG, "illegality action:"+action);
}
return super.onStartCommand(intent, flags, startId);
}
/* 顯示在通知欄 */
private void showNotification(boolean isStart){
createNotification(isStart);
}
/* 修改通知欄顯示 */
private void updateNotification(boolean isStart){
createNotification(isStart);
}
/* 從通知欄移除 */
public void removeNotification(){
stopForeground(true);
mTime = 0;
stopSelf();
}
/* 創建 Notification 對象 */
public void createNotification(boolean started){
if(mNotification == null){
mNotification = new Notification();
mNotification.icon = R.drawable.ic_launcher;
mNotification.flags |=Notification.FLAG_ONGOING_EVENT;//表示正處於活動中
Intent intent = new Intent(this,TestNotificationActivity.class);
//這裡要加入此 Flags,作用:當你通過點擊通知欄來喚起 Activity 時,對應的 Activity 啟動模式要為 android:launchMode="singleTop"
//於此 Flag 一起使用,可以保證你要啟動的 Activity 不會重新啟動,一個堆棧只有一個對應的實例對象
//使用這個標志,如果正在啟動的 Activity 的 Task 已經在運行的話,那麼,新的 Activity 將不會啟動;代替的,當前 Task 會簡單的移入前台。
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
mNotification.contentIntent = pendingIntent;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_layout);
contentView.setImageViewResource(R.id.icon, R.drawable.ic_launcher);
mNotification.contentView = contentView;
mTime = SystemClock.elapsedRealtime();
}
long time = mTime;
mNotification.contentView.setChronometer(R.id.text1, time, null, started);
mNotification.contentView.setTextViewText(R.id.text2, getString(started?R.string.time_running:R.string.time_pause));
//使用服務來啟動通知欄,這樣的好處時,
//1.當應用程序在後台運行時,startForeground可以使本應用優先級提高,不至於被系統殺掉
//2.當應用被異常掛掉時,可以保證通知欄對應的圖標被系統移除
startForeground(NOTIFICATIN_ID, mNotification);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:baselineAligned="false"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="65sp"
android:background="@android:drawable/status_bar_item_background"
android:id="@+id/layoutMain"
>
<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dip"
android:layout_marginRight="6dip" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Chronometer android:id="@+id/text1"
android:textColor="?android:attr/textColorPrimaryInverse"
android:textStyle="bold"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
/>
<TextView android:id="@+id/text2"
android:textColor="#ff6b6b6b"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
/>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.notioni.test.notification"
android:versionCode="1"
android:versionName="1.0" >
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".TestNotificationActivity"
android:launchMode="singleTop"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".NotificationService" android:exported="false"></service>
</application>
</manifest>
把通知交給 Service 的 startForeground 來呈現,而不是直接呼叫 NotificationManager 的 notify,有兩個明顯好處:
1. 當應用程式轉入後台運行時,startForeground 能提高程式的運行等級,不至於被系統回收;
2. 當應用程式因異常或其他未知原因終止時,ActivityManagerService 會把通知欄的圖標一併移除,不會出現程式已經關掉、圖標卻還掛在通知欄的尷尬情況。
從實現角度看,startForeground 會呼叫 ActivityManagerService.java 的 setServiceForeground 方法。該方法會保存 Notification 對象,再藉由 NotificationManager 的 notify 把通知顯示到狀態欄,然後把 Service 標記為 foreground = true。當應用異常退出時,ActivityManagerService 會監聽到應用死亡,並依據保存的 Notification 對象把通知欄的圖標移除。
ListView Item 多布局的實現方法
本節引言 作為 ListView 這個小節的最後一課,這次要帶來的是 ListView 多布局 Item 的實現。什麼叫 ListView Item 多布局?打個比方,Q
Android 仿外賣購物車實作全解:懸停標題、左右聯動與拋物線動畫
效果預覽 先盤點技術點 畫面看起來熱鬧,但真正需要花心思的其實就這幾塊: - 清單標題懸停 - 左右兩欄滑動聯動 - 加入商品時的拋物線動畫 - 底部彈出購物車清單
Android 影像處理實作:用 Options Menu 完成懷舊、浮雕、模糊、光照與素描效果
「隨手拍」這個專案想做成類似美圖秀秀那樣、底部一排效果按鈕的樣式。在動手做自訂 UI 之前,先用系統原生的 Options Menu 把幾種基本的影像處理效果跑起來,是個
淺談 Android 編碼規範與命名規範
在 Android 專案中,良好的編碼與命名規範能大幅提升維護效率。以下整理實務上常見的開發建議,適合團隊協作時參考。 一、編碼規範 1. 善用 string.x