AEQ-WEB

Android Notifications Java Code - Android Studio
Entwicklung
06.06.2018

Schalte Sprache zu: de German

Android Notifications

On this page we show you how to create a notification with Android. This article has nothing to do with a push Notification. Only a local notification is created. The code contains two classes. The MainActivity is the startpage of the app. When the button is pressed, the notification is created. The notification is displayed in the status bar and the ringtone is played. When the Notification is clicked, the Notifications-class opens with a Textview. Here could be a message for the user. It is also important to define the Notifications-class in the manifest.


Android Version API Version
4.0.3 15


First, two layout files must be created. For MainActivity, the layout contains only a button, and for the Notifications class, the layout contains only a TextView.


MainActivity.java:

package com.aeqweb.notify;

import ...

public class MainActivity extends Activity {
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Notify("Title", "You have pressed the button!");
            }
        });
    }

    private void Notify(String title, String text) {
        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_lncr)
                        .setSound(sound)
                        .setColor(0xffffffff)
                        .setContentTitle(title)
                        .setContentText(text);
        Intent notificationIntent = new Intent(this, Notification.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
    }
}

Notification.java:


package com.aeqweb.notify;

import ...

public class Notification extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
    }
}