Android通知无效

Car*_*ris 10 android android-notifications android-asynctask

我一直在尝试从ASyncTask成功上传通知,以便全天工作.我没有从我当前的代码中收到任何错误,但我无法通知通知栏(或其他任何地方).我在LogCat中没有收到任何消息,并且通知栏中没有显示任何通知.这是我的代码:

Notification mNotification = new Notification(icon, tickerText, when);

CharSequence contentTitle = "upload completed.";
CharSequence contentText = "upload completed.";

Intent notificationIntent = new Intent(context, CastrActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_NO_CREATE);
mNotification.contentIntent = contentIntent;
mNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
Run Code Online (Sandbox Code Playgroud)

这是从ASyncTask的onPostExecute()方法调用的.老实说,我对PendingIntent部分感到有点困惑.任何澄清我怀疑是不正确的代码将非常感激.

McI*_*osh 31

即使您的问题已经解决,我也会发布我如何解决通知未显示的问题,或许它可能有助于其他人阅读答案:

在我的通知大楼里,我错过了图标.一旦我添加了类似setSmallIcon(R.drawable.ic_launcher)通知的内容.


Mun*_*oor 4

我创建了该类来显示通知:

public class NotificationData {

    public static NotificationManager mNotificationManager;
    public static int SIMPLE_NOTFICATION_ID;
    private Context _context;

    public NotificationData(Context context) {
        _context = context;
    }

    public void clearNotification() {
        mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
    }

    public void SetNotification(int drawable, String msg, String action_string, Class cls) {
        mNotificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE);
        final Notification notifyDetails = new Notification(drawable, "Post Timer", System.currentTimeMillis());
        long[] vibrate = { 100, 100, 200, 300 };
        notifyDetails.vibrate = vibrate;
        notifyDetails.ledARGB = 0xff00ff00;
        notifyDetails.ledOnMS = 300;
        notifyDetails.ledOffMS = 1000;
     // notifyDetails.number=4;
        notifyDetails.defaults =Notification.DEFAULT_ALL;
        Context context = _context;
        CharSequence contentTitle = msg;
        CharSequence contentText = action_string;      
        Intent notifyIntent = new Intent(context,  cls);
     // Bundle bundle = new Bundle();
     // bundle.putBoolean(AppConfig.IS_NOTIFICATION, true);
        notifyIntent.putExtras(bundle);
        PendingIntent intent = PendingIntent.getActivity(_context, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
        notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
        mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);        
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用该类:

NotificationData notification; //create object
notification = new NotificationData(this);
notification.SetNotification(R.drawable.notification, "Notification Title", "Click to open", YourClassName.class);
Run Code Online (Sandbox Code Playgroud)

添加权限android.permission.VIBRATE