編輯:關於 Android 程式設計
本階段重點是三塊常被忽略但很實用的能力:發送通知、收發短信、調用相機與相冊。以下把每個 demo 的關鍵程式碼整理出來,方便日後回頭查。
發送通知的三個要素:取得 NotificationManager、構建 Notification、指定點擊後跳去哪裡(PendingIntent)。
public class MainActivity extends Activity {
private Button bt_notify;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_notify = findViewById(R.id.bt_notify);
bt_notify.setOnClickListener(v -> {
// 取得 NotificationManager
NotificationManager manager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 建立 Notification,帶圖示、標題文字與時間戳
Notification notification = new Notification(
R.drawable.ic_launcher, "hello zza", System.currentTimeMillis());
// 建構 PendingIntent,作為點擊通知時的跳轉依據
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(MainActivity.this, "Zza", "Hello", pi);
manager.notify(1, notification);
});
}
}
取消通知則在目標 Activity 中處理:
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
NotificationManager manager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);
}
}
notify 的第二個參數是通知 ID,cancel 時傳同一個 ID 即可精準取消。實務上更推薦用 NotificationCompat.Builder 建構,以兼顧各版本的相容性。
需要兩個權限:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
布局很直觀:兩行顯示收到的發件人與內容,下面輸入收件號碼與訊息並發送。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="10dp"
android:text="From:" />
<TextView
android:id="@+id/tv_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="10dp"
android:text="Content:" />
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="10dp"
android:text="To:" />
<EditText
android:id="@+id/et_to"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<EditText
android:id="@+id/et_msg"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1" />
<Button
android:id="@+id/bt_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="發送" />
</LinearLayout>
</LinearLayout>
關鍵在於「收」與「發」各需一個廣播接收器:收短信監聽系統的 SMS_RECEIVED 廣播,發短信則用自定義 action 接收發送結果。
public class MainActivity extends Activity {
private TextView sender;
private TextView content;
private IntentFilter receiveFilter;
private MessageReceiver messageReceiver;
private EditText to;
private EditText msgInput;
private Button send;
private IntentFilter sendFilter;
private SendStatusReceiver sendStatusReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sender = findViewById(R.id.tv_send);
content = findViewById(R.id.tv_content);
// 動態註冊接收短信的廣播
receiveFilter = new IntentFilter();
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
messageReceiver = new MessageReceiver();
registerReceiver(messageReceiver, receiveFilter);
// 註冊發送結果的廣播
sendFilter = new IntentFilter();
sendFilter.addAction("SENT_SMS_ACTION");
sendStatusReceiver = new SendStatusReceiver();
registerReceiver(sendStatusReceiver, sendFilter);
to = findViewById(R.id.et_to);
msgInput = findViewById(R.id.et_msg);
send = findViewById(R.id.bt_send);
send.setOnClickListener(v -> {
SmsManager smsManager = SmsManager.getDefault();
Intent sendIntent = new Intent("SENT_SMS_ACTION");
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, sendIntent, 0);
smsManager.sendTextMessage(to.getText().toString(), null,
msgInput.getText().toString(), pi, null);
});
}
/** 接收短信 */
class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String address = messages[0].getOriginatingAddress();
StringBuilder fullMessage = new StringBuilder();
for (SmsMessage smsMessage : messages) {
fullMessage.append(smsMessage.getMessageBody());
}
sender.setText(address);
content.setText(fullMessage.toString());
// 若要攔截系統短信,可在此呼叫 abortBroadcast();
}
}
/** 發送結果 */
class SendStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (getResultCode() == RESULT_OK) {
Toast.makeText(context, "發送成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "發送失敗", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(messageReceiver);
unregisterReceiver(sendStatusReceiver);
}
}
幾個值得記住的細節:長短信會被拆成多個 PDU,所以要把每段的 messageBody 拼接起來;動態註冊的廣播必須在 onDestroy 中反註冊,否則會記憶體洩漏;abortBroadcast() 可以攔截系統短信,但優先級要設得夠高才有效。
需要寫入外部儲存空間的權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/bt_take_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照" />
<Button
android:id="@+id/bt_choose_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="從相冊選擇圖片" />
<ImageView
android:id="@+id/iv_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
public class MainActivity extends Activity {
public static final int TAKE_PHONE = 1;
public static final int CROP_PHONE = 2;
private Button bt_take_phone;
private Button bt_choose_phone;
private ImageView iv_phone;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_take_phone = findViewById(R.id.bt_take_phone);
iv_phone = findViewById(R.id.iv_picture);
bt_take_phone.setOnClickListener(v -> {
// 建立 File 物件存放拍下的照片,這裡放在 SD 卡根目錄
File outputImage = new File(
Environment.getExternalStorageDirectory(), "temp.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHONE);
});
bt_choose_phone = findViewById(R.id.bt_choose_phone);
bt_choose_phone.setOnClickListener(v -> {
File outputImage = new File(
Environment.getExternalStorageDirectory(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
intent.putExtra("crop", true);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHONE);
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHONE:
if (resultCode == RESULT_OK) {
// 拍照後接著裁剪
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHONE);
}
break;
case CROP_PHONE:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(imageUri));
iv_phone.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
實測會發現相容性問題:部分品牌(例如華為)在點擊確認後拿不到圖片,三星則正常。這類問題的根因是各家 ROM 對裁剪 Intent 的實作差異。因此在正式專案中,更穩妥的做法是自己寫一個裁剪 Activity,用 Bitmap + Canvas 手動裁切,而不是依賴系統的 CROP action。另外 Android 7.0 之後 Uri.fromFile() 會觸發 FileUriExposedException,需改用 FileProvider。
Android 開發技巧:用 PopupWindow 封裝彈出式選單
由於介面的客製需求,Android 原生的彈出選單往往不敷使用,自定義選單幾乎是唯一選擇。本文分享一個把 PopupWindow 封裝成彈出選單的類別 PopMenu,以
用 Android-Rate 快速做出「去應用市場給好評」的引導彈窗
最近寫產品的文章少了些。家裡的小寶寶(麥麥)正處於愛咬人的階段,得花心思照顧;加上最近沉迷魔獸世界,寫作的時間就被擠掉了。今天偶然看到一個在 App 內提示使用者跳轉應用
實戰Android AIDL:打通跨進程通信的完整指南
先來描述一下我們要實現的效果:在一個應用中透過點擊按鈕,去操作另一個進程裡應用的音樂播放功能。 如圖所示,當我們點擊「播放」時,系統會去遠程調用我們提供的一個servi
Android 待辦事項 ToDo 應用實現解析
這個 ToDo 是從 MediaTek 項目中剝離出來的一份完整代碼,功能不算花哨,但結構相當規範,很適合拿來學習「列表 + 多選 + ActionMode + 分組」這