如何避免“getNotification”被弃用?

时间:2016-10-04 17:09:59

标签: android broadcastreceiver alarmmanager

我制作了警报应用程序并在MyAlarmService中包含以下代码。

public class MyAlarmService extends Service
{
    private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent arg0)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate()
    {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @SuppressWarnings("static-access")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Notification.Builder notification = new Notification.Builder(MyAlarmService.this);
        Intent intent1 = new Intent(this.getApplicationContext(),ReminderPage.class);
        PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,0);
        notification.setSmallIcon(R.drawable. notification_template_icon_bg)
                .setContentTitle("Music player")
                .setContentIntent(pendingNotificationIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification1 = notification.getNotification();
        notificationManager.notify(R.drawable.notification_template_icon_bg, notification1);
        mManager.notify(0, notification1);
        return super.onStartCommand(intent,flags, startId);
    }

    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
  1. 在onStart方法中,它总是有一个删除线。谷歌搜索后,我将onStart方法更改为onStartCommand(),但不确定这是否是正确的修改方式。
  2. getNotification已弃用。
  3. AndroidMainfest

     <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="10" />
    

    谢谢。

2 个答案:

答案 0 :(得分:4)

你可以试试吗,

NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context);
        notification = builder.setContentIntent(intent)
                .setSmallIcon(R.drawable.push_icon).setTicker(title).setWhen(when)
                .setAutoCancel(true).setContentTitle(title)
                .setContentText(message).build();
        notificationManager.notify(requestID, notification);

答案 1 :(得分:2)

您将Notification Builder命名为“ notification”。 因此,您只需将notification.getNotification()替换为notification.build()。

就是这样。在官方文档中进行了解释:https://developer.android.com/reference/android/app/Notification.Builder#getNotification()