在Android中处理API 10上的通知

时间:2013-06-06 13:33:58

标签: android

我放入onCreate()的代码如下:

if(Build.VERSION.SDK_INT >= 11)
        notifApiGT10();
    else
        notifApiLT10();

其中,

@SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    private void notifApiGT10() {
        // TODO Auto-generated method stub
        Notification.Builder builder ;
        NotificationManager notifier;
        builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher)
        .setWhen(System.currentTimeMillis())
        .setOngoing(true).setContentTitle("my Title").setContentText("my displayed text");

        notifier = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        if(Build.VERSION.SDK_INT>=11 && Build.VERSION.SDK_INT<=15)
            notifier.notify(1, builder.getNotification());
        else if (Build.VERSION.SDK_INT > 15)
            notifier.notify(1, builder.build());
    }

private void notifApiLT10()
    {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .setContentText("is actually in use")
        .setContentTitle("my Title")
        .setOngoing(true)
        .setTicker("my ticker")
        .setSmallIcon(R.drawable.ic_launcher);
        Notification notif = builder.getNotification();
        NotificationManager mN = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        mN.notify(1, notif);

    }

以上代码无法在API 10上运行。我的设备正在运行Gingerbread,而且它没有使用它。 我想知道为什么......任何专家?

Notification notification = new Notification(R.drawable.ic_launcher, "my ticker", System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
Intent i = new Intent(this,Main.class);
PendingIntent pd = PendingIntent.getActivity(this, 1, null, Intent.FLAG_ACTIVITY_NEW_TASK); 


notification.setLatestEventInfo(context, "my title", "my text", pendingintent);
NotificationManager mN = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mN.notify(1,notification);

以上解决方案解决了我的问题, 即使你不想在点击时运行任何东西,你应该将pendingintent放在方法setLatestEventInfo中,但是在你注意到的pd中,在第3个字段中,我已将intent设置为null

1 个答案:

答案 0 :(得分:3)

您是否尝试过使用NotificationCompat.Builder.build()? {/ 3}}已被弃用。

仅供参考,上次我使用NotificationCompat.Builder时,setNumber()无法正常工作,我最终直接在较旧的设备上构建Notification。

编辑:尝试直接在旧设备上使用通知类,因为NotificationCompat.Builder.getNotification()(API&lt; = 10)只使用构建器中的4个字段,无论设置了多少。