Search code examples
androidnotificationsnotifynotificationmanager

Issue with Notification Manager on android


I'm trying to notify using a button, but both Notification and setLatestEventInfo is deprecated.

Two errors:

1.The constructor Notification(int, CharSequence, long) is deprecated Notification notify = new Notification(android.R.drawable.stat_notify_more, "Hello all", System.currentTimeMillis());

2.The method setLatestEventInfo(Context, CharSequence, CharSequence, PendingIntent) in the type Notification is not applicable for the arguments (Context, CharSequence, CharSequence, Intent) notify.setLatestEventInfo(context, title, details, intent);

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {   
        @Override
        public void onClick(View v) {
            NotificationManager ns = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notify = new Notification(android.R.drawable.stat_notify_more, "Hello all", System.currentTimeMillis());
            Context context = MainActivity.this;
            CharSequence title ="you have be notified";
            CharSequence details = "Continue your work";
            Intent intent = new Intent(context,MainActivity.class);
            PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
            notify.setLatestEventInfo(context, title, details, intent);
            ns.notify(0,notify);


        }
    });
}

API LEVELS:

       android:minSdkVersion="11"
       android:targetSdkVersion="17"

What is the alternative?


Solution

  • 1. The constructor was deprecated in api level 11. so you should use Notification.Builder.

    for e.g.

    Notification notification = new Notification.Builder(mContext)
         .setContentTitle("New mail from " + sender.toString())
         .setContentText(subject)
         .setSmallIcon(R.drawable.new_mail)
         .setLargeIcon(aBitmap)
         .build();
    

    2. in your code you are passing the intent instead of pending in setLatestEventInfo

    ....
    Intent intent = new Intent(context,MainActivity.class);
            PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
            notify.setLatestEventInfo(context, title, details, pending);
            ns.notify(0,notify);
    ....