標籤:
安卓系統通知使用者三種方式:
1.Toast Notification
2.Dialog Notification
3.Status Bar Notification Status Bar Notification,狀態列通知
發送一個狀態列通知必須用到兩個類:NotificationManager,Notification
1.NotificationManager是一個系統Service,必須通過getSystemService()擷取
NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
2.Notification是具體的狀態列通知對象
調用NotificationManager的notify()方法建立Notification
兩部分:
①:狀態列通知
notification.icon=R.drawable.ic_launcher;
notification.tickerText="My First Notification";
notification.when=System.currentTimeMillis();
②:下拉通知清單和點擊跳轉:
兩種方式:
一:setLatestEventInfo()方法
Context context = getApplicationContext();
CharSequence contentTitle="Notification";
CharSequence contentText="Notification Context";
Intent intent=new Intent(Main.this,Turn.class);
PendingIntent pendingIntent=PendingIntent.getActivity(Main.this, 0, intent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent);
二:自訂通知欄
notification.flags=Notification.FLAG_AUTO_CANCEL;使用者點擊後通知自動取消
設定兩個變數contentView和contentIntent
RemoteViews contenView=new RemoteViews(getPackageName(), R.layout.notification_layout);
contenView.setImageViewResource(R.id.icon, R.drawable.ic_launcher);
contenView.setTextViewText(R.id.contentText, "自訂通知");
notification.contentView=contenView;
Intent intent1=new Intent(Main.this,Turn.class);
PendingIntent pendingIntent1=PendingIntent.getActivity(Main.this, 0, intent1, 0);
notification.contentIntent=pendingIntent1;
Tips:
可能遇到的錯誤:Couldn‘t expand RemoteViews for:
檢查是否是RemoteViews對應的layout裡使用了它不支援的組件
檢查RemoteViews對應的layout布局檔案是否有基本錯誤,例如忘記聲明寬高等
安卓狀態列通知Status Bar Notification