首页 > 解决方案 > 关于android上发布通知的编码问题

问题描述

我需要重写所有不推荐使用的方法和类。

private void showNotification(Peer peer, int id) {
    CharSequence text = getString(id) + " " + peer.getName();
    Notification notification = new Notification(R.drawable.notification, text, System.currentTimeMillis());

    notification.flags |= Notification.FLAG_AUTO_CANCEL; 

    Intent intent = new Intent(this, IPsecToolsActivity.class); //intent.setAction(ACTION_NOTIFICATION);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

    notification.setLatestEventInfo(this, getText(R.string.native_service_label), text, contentIntent);    //setLatestEventInfo method has been deprecated

    // Send the notification.
    mNM.notify(peer.getName(), R.string.notify_peer_up, notification);
}

请注意,通知已弃用,太旧了。无法使用 setLatestEventInfo 方法。我需要帮助以另一种方式重写它。

我重写的方式如下:如果我是对的,请告诉我。

private void showNotification(Peer peer, int id) {
    CharSequence text = getString(id) + " " + peer.getName();

    Context context = this; 
    Notification notification = new Notification.Builder(context)    
            .setContentText(text)
            .setSmallIcon(R.drawable.notification)
            .setWhen(System.currentTimeMillis())
            .build();


    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    Intent intent = new Intent(this, IPsecToolsActivity.class);
    //intent.setAction(ACTION_NOTIFICATION);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            intent, 0);

    // Send the notification.
    mNM.notify(peer.getName(), R.string.notify_peer_up, notification); 
}

标签: android

解决方案


推荐阅读