[英]Android notification isn't showing up
我試圖在我的android應用中顯示一條小通知,但我看不到任何東西。 MainActivity
類具有一個名為activity
的static field
,它等於this
。 message.data
只是從對象中提取的。 這就是我所說的:
sendNotification(MainActivity.activity.getApplicationContext(),
null,
message.data,
message.data,
1, true, true, true, 0);
這是肉:
public static void sendNotification(Context caller, Class<?> activityToLaunch, String title, String msg, int numberOfEvents,boolean sound, boolean flashLed, boolean vibrate,int iconID) {
NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification(R.drawable.ic_launcher,"Notification",System.currentTimeMillis());
notify.icon = iconID;
notify.tickerText = title;
notify.when = System.currentTimeMillis();
notify.number = numberOfEvents;
notify.flags |= Notification.FLAG_AUTO_CANCEL;
if (sound) notify.defaults |= Notification.DEFAULT_SOUND;
if (vibrate) notify.vibrate = new long[] {100, 200, 300};
if (flashLed) {
notify.flags |= Notification.FLAG_SHOW_LIGHTS;
notify.ledARGB = Color.CYAN;
notify.ledOnMS = 500;
notify.ledOffMS = 500;
}
int NOTIFICATION_ID = 1232;
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(caller, 0, notificationIntent, 0);
notify.setLatestEventInfo(caller, title, msg, contentIntent);
notifier.notify(NOTIFICATION_ID, notify);
}
我可以記錄消息,所以我知道它會被調用,但是,我是android開發的初學者,很可能缺少關鍵部分。 我在模擬器android 2.2上運行。 這一切都在我鏈接到在后台運行的cordova的插件對象中(如果有的話)。
我為此創建了一個新類:
public class StatusNotificationIntent {
public static Notification buildNotification( Context context, CharSequence tag, CharSequence contentTitle, CharSequence contentText) {
int icon = R.drawable.notification;
long when = System.currentTimeMillis();
Notification noti = new Notification(icon, contentTitle, when);
noti.flags |= flag;
PackageManager pm = context.getPackageManager();
Intent notificationIntent = pm.getLaunchIntentForPackage(context.getPackageName());
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.putExtra("notificationTag", tag);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
noti.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
return noti;
}
}
我用這個功能來稱呼它
public void showNotification( CharSequence tag, CharSequence contentTitle, CharSequence contentText, int flag) {
String ns = Context.NOTIFICATION_SERVICE;
context = cordova.getActivity().getApplicationContext();
mNotificationManager = (NotificationManager) context.getSystemService(ns);
Notification noti = StatusNotificationIntent.buildNotification(context, tag, contentTitle, contentText);
mNotificationManager.notify(tag.hashCode(), noti);
}
ClassStacker和David Wasser(在評論中)指出使用正確的Intent和正確的上下文的組合可以解決此問題是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.