I want to create a dynamic notification on Android, where I can change the title and text that is displayed, via parameters .
I'm currently doing this:
Home.class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Intent i = new Intent(Home.this, BroadcastManager.class);
sendBroadcast(i); //PASSAR COMO PARÂMETRO A MENSAGEM QUE EU QUERO QUE SEJA EXIBIDA
}
Pass parameters in this line sendBroadcast(i);
BroadcastManager.class
public class BroadcastManager extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
Notification(context, "Mensagem"); // RECEBER AQUI, OS PARAMETROS PASSADOS
}
public void Notification(Context context, String message){
String strtitle = context.getString(R.string.app_name);
Intent intent = new Intent(context, NotificationView.class);
intent.putExtra("title", strtitle);
intent.putExtra("text", message);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker(message)
.setContentTitle("Titulo da notificação") //RECEBER AQUI, OS PARAMETROS PASSADO
.setContentText(message)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
}
Receive in these lines .setContentTitle("Titulo da notificação")
and .setContentText(message)
the parameters passed
NotificationView.class
public class NotificationView extends Activity {
String title;
String text;
TextView txttitle;
TextView txttext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notificationview);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancel(0);
// Retrive the data from MainActivity.java
Intent i = getIntent();
title = i.getStringExtra("title");
text = i.getStringExtra("text");
// Locate the TextView
txttitle = (TextView) findViewById(R.id.title);
txttext = (TextView) findViewById(R.id.text);
// Set the data into TextView
txttitle.setText(title);
txttext.setText(text);
}
}
I relied on this tutorial: link