系统服务和通知栏
使用系统服务来监听来电状态:
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:// 通话状态
Toast toast1 = Toast.makeText(MainActivity.this, "现在开始通话",
Toast.LENGTH_LONG);
toast1.show();
break;
case TelephonyManager.CALL_STATE_RINGING:// 来电状态
Toast toast2 = Toast.makeText(MainActivity.this, "收到一个来电",
Toast.LENGTH_LONG);
toast2.show();
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}, PhoneStateListener.LISTEN_CALL_STATE);
通知栏也是一种系统服务
1.获取通知栏服务
NotificationManager nm;
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2.包装一个通知发送到通知栏
//创建新通知的时候制订了图标、显示文字和添加通知的时间
Notification ntf = new Notification(
android.R.drawable.ic_notification_clear_all,
"测试通知", 123456);
//这样在读取这个通知后,该图标就会从通知栏消失
ntf.flags = Notification.FLAG_AUTO_CANCEL;
//读取通知的时候显示的界面,(也是用一个意图来跳转的)
Intent intent = new Intent(MainActivity.this,
Activity2.class);
//包装通知的消息
PendingIntent pi = PendingIntent.getActivity(
MainActivity.this, 0, intent, 0);
ntf.setLatestEventInfo(getApplicationContext(),
"contentTitle", "contentText", pi);
//把消息发送到通知栏
nm.notify(0, ntf);