How to create notifications?

Asked

Viewed 4,072 times

1

I’m making apps only to test some functions for Android and would like to know how to create notifications in the status bar.

My Java code and a standard code that only calls the XML file:

package com.bandicootapps.nav;

import android.app.*;
import android.os.*;
import android.view.*;
import android.webkit.*;
import android.widget.*;

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

What do I add to when the app starts a notification? I’d also like you to have an icon in that notification.

  • The documentation has a guide complete. You can also see the numerous questions already asked here by searching for the tag android-notification

2 answers

3


Example:

public class MainActivity extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       NotificationCompat.Builder mBuilder =
           new NotificationCompat.Builder(this)
           .setSmallIcon(R.drawable.notification_icon)
           .setContentTitle("My notification")
           .setContentText("Hello World!");

       NotificationCompat.Builder mBuilder;
       int mNotificationId = 001;

       NotificationManager mNotifyMgr =
           (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

       mNotifyMgr.notify(mNotificationId, mBuilder.build());
   }
}

References and more information on:

Google Developers - Notifications

Google Developers - Building a Notification

1

This is a simple example I use:

/* @param id identificacao da notificacao 
* @param title titulo da notificacao
* @param message mensagem a ser exibida
* @param intent se quiser uma tela que ser invocada quando clicar na notificacao*/

    public static void onCreateNotify(Context context, int id, CharSequence title, CharSequence message, Intent intent ) {

//          intent.putExtra(key, valueKey);

       PendingIntent pIntent = PendingIntent.getActivity(context, Constantes.SUCESS, intent, PendingIntent.FLAG_UPDATE_CURRENT);

       NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
               .setSmallIcon(R.drawable.ic_evendas_att)
               .setContentTitle(title)
               .setContentText(message)
               .setAutoCancel(true)
               .setContentIntent(pIntent)
               .setVibrate(new long[]{ 100, 250, 100, 500 })
               .setLights(100, 500, 100);

       NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(id, builder.build());

    }

but details here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.