「android初心者」アプリ開発でPendingIntentを利用するサンプルコード

1.システム通知
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); int icon = android.R.drawable.stat_notify_chat; long when = System.currentTimeMillis() + 2000;
Notification n = new Notification(icon, “通知demoのお知らせ", when);
n.defaults = Notification.DEFAULT_SOUND;
n.flags |= Notification.FLAG_AUTO_CANCEL;

Intent openintent = new Intent(this, DemoList.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, openintent, PendingIntent.FLAG_CANCEL_CURRENT);
n.setLatestEventInfo(this, “通知title", “通知text", pi);
nm.notify(0, n);

2.メッセージングシステム

private final static String SEND_ACTION = “send"; private final static String DELIVERED_ACTION = “delivered"; private void sendSms(String receiver, String text) {
SmsManager s = SmsManager.getDefault();
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SEND_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED_ACTION),
PendingIntent.FLAG_CANCEL_CURRENT); // 送信完了 registerReceiver(new BroadcastReceiver() {

@Override public void onReceive(Context context, Intent intent) { switch (getResultCode()) { case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), “Send Success!", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), “Send Failed because generic failure cause.",
Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), “Send Failed because service is currently unavailable.",
Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), “Send Failed because no pdu provided.", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), “Send Failed because radio was explicitly turned off.",
Toast.LENGTH_SHORT).show(); break; default:
Toast.makeText(getBaseContext(), “Send Failed.", Toast.LENGTH_SHORT).show(); break;
}
}
}, new IntentFilter(SEND_ACTION));
// 受信完了
registerReceiver(new BroadcastReceiver() {

@Override public void onReceive(Context context, Intent intent) { switch (getResultCode()) { case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), “Delivered Success!", Toast.LENGTH_SHORT).show(); break; default:
Toast.makeText(getBaseContext(), “Delivered Failed!", Toast.LENGTH_SHORT).show(); break;
}
}
}, new IntentFilter(DELIVERED_ACTION)); //sentPI送信成功、deliveredPI受信成功
s.sendTextMessage(receiver, null, text, sentPI, deliveredPI);
}

Android

Posted by arkgame