2

我输入的代码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中你注意到了,在第三个字段中,我已经将intent设置为null

4

1 回答 1

3

您是否尝试过使用 NotificationCompat.Builder.build()?NotificationCompat.Builder.getNotification()已弃用。

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

编辑:尝试直接在旧设备上使用 Notification 类,因为NotificationCompatImplBase (API <= 10) 仅使用构建器中的 4 个字段,无论设置了多少。

于 2013-06-06T13:54:17.937 回答