Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 智能短信應用實作(二):會話刪除、自定義對話框與簡訊發送

編輯:關於 Android 程式設計

本篇接續短信應用的開發,處理幾個實務上一定會遇到的環節:批次刪除會話、打造可重複使用的自定義對話框、帶進度條的刪除流程、會話詳情頁的資料傳遞與異步載入,以及簡訊的發送。

一、刪除選中的會話

刪除動作本身就是操作資料庫,用 ContentResolver 即可,關鍵在於「要刪的 URI 是什麼」。短信的 URI 是:

Uri URI_SMS = Uri.parse("content://sms");

由於同一個聯絡人的所有短信共用同一個 thread_id,因此只要拿 thread_id 當條件,一次就能清掉這個人的全部對話。寫短信需要 SEND_SMS 相關權限,讀寫短信則需要 READ_SMS/WRITE_SMS,別忘了在 Manifest 中宣告。

先在 Fragment 中處理點擊:取出使用者勾選的會話 id 集合,若為空就直接返回,否則呼叫刪除方法。

case R.id.bt_conversation_delete:
    selectedConversationId = adapter.getSelectedConversationId();
    if (selectedConversationId.size() == 0) {
        return;
    }
    deleteAll();
    break;

public void deleteAll() {
    for (Integer integer : selectedConversationId) {
        String where = "thread_id=" + integer;
        getActivity().getContentResolver().delete(ConstantValues.URI_SMS, where, null);
    }
}

二、自定義對話框的骨架

專案裡對話框會有很多個,因此先抽一個抽象基底類別,把生命週期切成 initView、initListener、initData 三段,並統一處理點擊:

public abstract class BaseDialog extends AlertDialog implements View.OnClickListener {
    public BaseDialog(Context context) {
        super(context, R.style.BaseDialog);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initListener();
        initData();
    }

    public abstract void initView();
    public abstract void initListener();
    public abstract void initData();
    public abstract void processClick(View v);

    public void onClick(View v) {
        processClick(v);
    }
}

這裡有個容易搞錯的細節:要實作的是 View.OnClickListener,而不是 DialogInterface 的點擊監聽。因為對話框是自定義的,上面的按鈕也是我們自己放的 Button,自然要用 View 的監聽器。

接著寫 dialog_comfirm.xml:一個寬 240dp 的垂直 LinearLayout,由上到下是標題 TextView、內容 TextView、一條 1dp 分隔線,以及一組水平排列的取消/確定按鈕。

為了讓對話框有圓角,新增一個 drawable,用 shape 定義:

shape android:shape="rectangle"
   corners android:radius="8dp"
   solid   android:color="#cccccc"

如果每個對話框都要寫一次這段就太囉嗦了,所以改用主題統一掛上:

style name="BaseDialog" parent="@android:style/Theme.Dialog"
   item name="android:windowBackground": @drawable/dialog_confrim

BaseDialog 的建構式再把這個 style 傳給 AlertDialog——AlertDialog 其中一個建構式本來就接受 Theme 參數,所以直接 super(context, R.style.BaseDialog) 即可。要注意:主題裡已經設定了 windowBackground,佈局檔上的 android:background 就要拿掉,否則會把圓角背景蓋回來。

三、按鈕的九宮格背景與點擊效果

給 Button 加上 selector 背景後會發現左下與右下不再是圓角,因此需要分別為左右兩顆按鈕各寫一組 shape,再用 selector 組裝:

selector
   item android:drawable="@drawable/bg_right_bt"      android:state_pressed="false"
   item android:drawable="@drawable/bg_right_bt_press" android:state_pressed="true"

四、讓對話框可被客製:標題、內容與監聽介面

透過建構式把 title 與 message 傳進來,再用 initData() 填到畫面上:

public class ComfirmDialog extends BaseDialog {
    private String title;
    private String message;
    private TextView tv_dialog_title;
    private TextView tv_dialog_msg;
    private Button bt_dialog_cancel;
    private Button bt_dialog_confirm;
    private DialogBtListener onConfrimListener;

    public ComfirmDialog(Context context, String title, String message,
                         DialogBtListener onConfrimListener) {
        super(context);
        this.title = title;
        this.message = message;
        this.onConfrimListener = onConfrimListener;
    }

    public void initView() {
        setContentView(R.layout.dialog_comfirm);
        tv_dialog_title  = (TextView) findViewById(R.id.tv_dialog_title);
        tv_dialog_msg    = (TextView) findViewById(R.id.tv_dialog_msg);
        bt_dialog_cancel = (Button) findViewById(R.id.bt_dialog_cancel);
        bt_dialog_confirm= (Button) findViewById(R.id.bt_dialog_confirm);
    }

    public void initListener() {
        bt_dialog_cancel.setOnClickListener(this);
        bt_dialog_confirm.setOnClickListener(this);
    }

    public void initData() {
        tv_dialog_title.setText(getTitle());
        tv_dialog_msg.setText(getMessage());
    }

    public void processClick(View v) {
        switch (v.getId()) {
            case R.id.bt_dialog_cancel:
                if (onConfrimListener != null) onConfrimListener.onCancle();
                break;
            case R.id.bt_dialog_confirm:
                if (onConfrimListener != null) onConfrimListener.onConfrim();
                break;
        }
        dismiss();   // 不論確定或取消都要關閉
    }
}

因為不希望把點擊行為寫死,所以另外定義一個監聽介面,讓呼叫方自行決定要做什麼;日後要換行為,只要重新呼叫 setter 換掉介面即可。

public interface DialogBtListener {
    void onCancle();
    void onConfrim();
}

於是刪除的呼叫處就能寫成:

public void showDelete() {
    ComfirmDialog dialog = new ComfirmDialog(getActivity(), "提示", "請確定是否要刪除",
        new DialogBtListener() {
            public void onConfrim() { deleteAll(); }
            public void onCancle()  { }
        });
    dialog.show();
}

五、把刪除搬到子執行緒,並用 Handler 更新 UI

資料庫操作是耗時動畫,筆數一多就會 ANR,所以必須放到子執行緒;而 UI 只能在主執行緒更新,因此用 Handler 回報結果。另外,刪完之後集合裡的 id 已經失效,一定要清空,否則下次查詢會出問題。

private static final int WHAT_DELETE_COMPLETE = 0;

private Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case WHAT_DELETE_COMPLETE:
                adapter.setIsSelectMode(false);
                showEditMenu();
                break;
        }
    }
};

public void deleteAll() {
    new Thread(new Runnable() {
        public void run() {
            for (Integer integer : selectedConversationId) {
                String where = "thread_id=" + integer;
                getActivity().getContentResolver().delete(ConstantValues.URI_SMS, where, null);
            }
            selectedConversationId.clear();
            handler.sendEmptyMessage(WHAT_DELETE_COMPLETE);
        }
    }).start();
}

六、加上刪除進度對話框

進度對話框與確認對話框結構幾乎一樣,只要把中間的 TextView 換成 ProgressBar,並把其中一顆按鈕改成「取消中斷」。要讓進度條變成紅色,得先看系統怎麼定義:

style name="Widget.ProgressBar.Horizontal"
   indeterminateOnly : false
   progressDrawable  : @android:drawable/progress_horizontal
   minHeight / maxHeight : 20dip

點進 progress_horizontal 會看到它是一個 layer-list,內含 background、secondaryProgress、progress 三層,每一層都用 gradient 做漸層。我們自己複製一份,把 progress 那層的 gradient 換成 solid 固定色即可:

layer-list
   item android:id="@android:id/background"
      shape / corners android:radius="5dip" / solid android:color="#aa666666"
   item android:id="@android:id/progress"
      clip / shape / corners android:radius="5dip" / solid android:color="#f00"

DeleteDialog 的實作延續同樣的模板,額外對外暴露一個更新進度的方法,讓 Fragment 在刪除過程中不斷呼叫:

public void serProgress(int progerss) {
    tv_delete_title.setText("正在刪除(" + progerss + "/" + Maxprogerss + ")");
    pb_delete_.setProgress(progerss);
}

中斷的實作方式是用一個旗標:按下中斷就把它設為 true,執行緒在迴圈中檢查旗標並 break。由於更新進度需要帶資料,因此不能再用空訊息,改用 Message.arg1 攜帶目前進度:

private static final int WHAT_UPDATA_PROGRESS = 1;
private int count = 1;
boolean isStop = false;

public void deleteAll() {
    dialog = new DeleteDialog(getActivity(), selectedConversationId.size(),
        new DeleteDialogListener() {
            public void interrupe() { isStop = true; }
        });
    dialog.show();
    new Thread(new Runnable() {
        public void run() {
            for (Integer integer : selectedConversationId) {
                SystemClock.sleep(1000);          // 實務上請移除,這裡只是方便觀察進度
                if (isStop) { isStop = false; break; }
                String where = "thread_id=" + integer;
                getActivity().getContentResolver().delete(ConstantValues.URI_SMS, where, null);
                Message msg = Message.obtain();
                msg.what = WHAT_UPDATA_PROGRESS;
                msg.arg1 = count++;
                handler.sendMessage(msg);
            }
            selectedConversationId.clear();
            handler.sendEmptyMessage(WHAT_DELETE_COMPLETE);
        }
    }).start();
}

七、會話詳情頁:傳值與異步查詢

點擊會話時,因為用的是 CursorAdapter,可以直接用 getItem(position) 拿到 Cursor,再封裝成 ConversationBean,把 address 與 thread_id 帶到詳情頁:

public void onItemClick(AdapterView parent, View view, int position, long id) {
    if (adapter.getIsSelectMode()) {
        adapter.SelectSingle(position);
    } else {
        Intent intent = new Intent(getActivity(), ConversationDataActivity.class);
        Cursor cursor = (Cursor) adapter.getItem(position);
        ConversationBean bean = ConversationBean.creatConversationCursor(cursor);
        intent.putExtra("address", bean.getAddress());
        intent.putExtra("thead_id", bean.getThread_id());
        startActivity(intent);
    }
}

詳情頁的標題欄可重複利用,因此獨立成 layout_titlebar.xml,再用 include 引入。查詢該會話的所有短信時,記得用異步版本避免卡住主執行緒:

String[] projection = { "_id", "body", "type", "date" };
String selection = "thread_id =" + thread_id;
SimpleQueryHandler queryHandler = new SimpleQueryHandler(getContentResolver());
queryHandler.startQuery(0, null, ConstantValues.URI_SMS, projection, selection, null, "date");

排序用預設的升序即可,這樣最新的訊息會落在最下方。_id 是 CursorAdapter 的必要欄位,其餘三個是畫面顯示所需。

八、幾個實作細節與踩坑紀錄

1. 去掉 ListView 的分隔線與點擊高亮。

listView
   android:divider="@android:color/transparent"
   android:listSelector="@android:color/transparent"

2. 時間不要每條都顯示。把時間格式化抽成獨立方法,再定義一個間隔門檻(例如 3 分鐘),只有與上一封相差超過門檻才顯示時間戳:

private static final int DURTION = 3 * 60 * 1000;

if (cursor.getPosition() == 0) {
    showDate(context, holder, smsBean);           // 第一條沒有「上一條」,直接顯示
} else {
    long date = getPreviousDate(cursor.getPosition());
    if (smsBean.getDate() - date > DURTION) {
        holder.tv_desconversation_date.setVisibility(View.VISIBLE);
        showDate(context, holder, smsBean);
    } else {
        holder.tv_desconversation_date.setVisibility(View.GONE);
    }
}

3. 進入頁面時要自動捲到最底。用 setSelection(cursor.getCount()),但關鍵是「什麼時候呼叫」——若此時 cursor 還是空的,這行完全無效。由於查詢完成後是透過 changeCursor() 把資料交給 Adapter,因此正解是在 Adapter 中覆寫它:

public void changeCursor(Cursor cursor) {
    super.changeCursor(cursor);
    lv.setSelection(cursor.getCount());
}

要注意 changeCursor 只在查詢完成時觸發,簡訊內容變動後不會重新呼叫。

4. 軟鍵盤遮住輸入框。可以讓 ListView 使用 setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL),內容變動時自動捲到最新位置;也可以在 Manifest 中用 windowSoftInputMode 調整 Activity 與軟鍵盤的關係,實務上通常把一個 state 值與一個 adjust 值組合成 triad 使用:

  • stateUnspecified/stateUnchanged/stateHidden/stateAlwaysHidden/stateVisible/stateAlwaysVisible:控制 Activity 出現時鍵盤的顯示狀態。
  • adjustUnspecified/adjustResize/adjustPan:前者交給系統決定;adjustResize 會縮放畫面讓出鍵盤空間;adjustPan 則是平移內容讓焦點不被遮住。

九、發送簡訊

把發送邏輯集中到 SmsDao。這裡有兩個重點:長簡訊要先用 divideMessage 切片;而 SmsManager 的 sendTextMessage 只負責送出,不會寫入資料庫,所以畫面上看不到自己剛發的那一封,必須自己插入一筆。

public class SmsDao {
    public static void sendSms(String address, String body, Context context) {
        SmsManager manager = SmsManager.getDefault();
        Intent intent = new Intent("com.chen.text.sendsms");
        ArrayList smss = manager.divideMessage(body);
        PendingIntent sentIntent =
                PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        for (String text : smss) {
            manager.sendTextMessage(address, null, text, sentIntent, null);
            addSms(context, text, address);
        }
    }

    public static void addSms(Context context, String text, String address) {
        ContentValues values = new ContentValues();
        values.put("address", address);
        values.put("body", text);
        values.put("type", ConstantValues.TYPE_SEND);
        context.getContentResolver().insert(ConstantValues.URI_SMS, values);
    }
}

寄送結果要靠 PendingIntent 觸發的廣播來接收,因此另外寫一個 BroadcastReceiver,用 getResultCode() 判斷成功與否:

public class SmsSendReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if (getResultCode() == Activity.RESULT_OK) {
            ToastUtils.showToast(context, "發送成功");
        } else {
            ToastUtils.showToast(context, "發送失敗");
        }
    }
}

PendingIntent 的 flag 值得記一下:FLAG_ONE_SHOT 代表只能使用一次;FLAG_NO_CREATE 在對應 Intent 不存在時回傳 null;FLAG_CANCEL_CURRENT 會先取消舊的再建立新的;而最常用的是 FLAG_UPDATE_CURRENT,若描述已存在就更新其中的 extras——少了它,第二次之後 extras 永遠會是第一次那組值。

十、新建簡訊頁與聯絡人選擇

發送頁的輸入框改用 AutoCompleteTextView 就能做到號碼自動補全。它本質上就是一個 EditText,顯示內容一樣靠 Adapter,因此沿用 CursorAdapter,並透過 setFilterQueryProvider 在每次輸入時回查:

adapter.setFilterQueryProvider(new FilterQueryProvider() {
    public Cursor runQuery(CharSequence constraint) {
        String[] projection = { "data1", "display_name", "_id" };
        String selection = "data1 like '%" + constraint + "%'";
        return getContentResolver().query(Phone.CONTENT_URI, projection, selection, null, null);
    }
});

這個回呼在每次文字變動(包含刪字)時都會觸發。預設要輸入滿兩個字元才查詢,可在佈局中加上 android:completionThreshold="1" 改為一個字元就查。點選下拉項目的行為由 convertToString(Cursor) 決定,覆寫它並回傳號碼欄位,就能把號碼填進輸入框。

若想直接叫出系統通訊錄,用 ACTION_PICK 搭配 phone 的 MIME 型別即可:

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("vnd.android.cursor.dir/phone");
startActivityForResult(intent, 0);

回傳的 data 中帶的是所選聯絡人的 URI,但查下去會發現裡面只有 _id、display_name、has_phone_number,並沒有號碼,因此必須再用 _id 去 Phone.CONTENT_URI 查一次 data1:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri uri = data.getData();
    if (uri != null) {
        Cursor cursor = getContentResolver().query(uri, new String[] { "_id", "has_phone_number" }, null, null, null);
        cursor.moveToFirst();
        String _id = cursor.getString(0);
        int has_phone_number = cursor.getInt(1);
        if (has_phone_number == 0) {
            ToastUtils.showToast(getApplicationContext(), "沒有號碼");
        } else {
            Cursor query = getContentResolver().query(Phone.CONTENT_URI,
                    new String[] { "data1" }, "contact_id=" + _id, null, null);
            query.moveToFirst();
            actv_newmsg_address.setText(query.getString(0));
        }
    }
    et_newmsg_body.requestFocus();   // 把焦點移回內容框,避免又跳出自動補全清單
    super.onActivityResult(requestCode, resultCode, data);
}

這裡不需要判斷 cursor 是否為空,因為既然使用者能選到這個聯絡人,資料必然存在。最後記得用 ScrollView 包住表單內容,否則螢幕上的軟鍵盤會把發送鈕整個蓋住。

小結

這一段把短信應用的骨幹補齊了:刪除走 ContentResolver 並丟到子執行緒,進度回報交給 Handler,對話框抽成 BaseDialog 加監聽介面的模板,會話詳情用 SimpleQueryHandler 做異步查詢並在 changeCursor 中處理捲動,發送則是 SmsManager 加上自行寫入資料庫的補償動作。這些模式在別的資料型 App 裡幾乎可以原封不動地套用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved