星期二, 十一月 06, 2012

Android 2.3.3 以上通用Notification 生成 代码.使用NotificationCompat.Builder

//notification unique id 
//The IDs must be unique only within the namespace of your .apk's package nam
//这个ID只需要在你自己的app 空间里唯一即可,不是整个系统唯一
public void setupNotification(Context ctx)
    {
        Intent notificationIntent = new Intent(ctx, StartGateActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(ctx,
                0, notificationIntent,
                0);

        NotificationManager nm = (NotificationManager) ctx
                .getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(100);
        Resources res = ctx.getResources();
        CharSequence text = res.getString(R.string.nf_text);
        CharSequence contentTitle = res.getString(R.string.nf_title);
        CharSequence ticket = res.getString(R.string.nf_ticket);
        NotificationCompat.Builder builder= new NotificationCompat.Builder(ctx);

        builder.setContentTitle(contentTitle)
        .setContentText(text)
        .setSmallIcon(R.drawable.ic_launcher)
        .setOngoing(true) //this flag notification record  can't be clear
        .setAutoCancel(true)
        .setWhen(System.currentTimeMillis())
        .setTicker(ticket)
        .setContentIntent(contentIntent);
        Notification nf = builder.build();       
        nm.notify(100, nf);
    }