Skip to content

Instantly share code, notes, and snippets.

@audinue
Created March 2, 2023 12:40
Show Gist options
  • Save audinue/d50904876da86642164215d28fd3d2d7 to your computer and use it in GitHub Desktop.
Save audinue/d50904876da86642164215d28fd3d2d7 to your computer and use it in GitHub Desktop.
package com.example.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class NotificationExample extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
LinearLayout layout = new LinearLayout(this);
{
Button button = new Button(this);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showNotification();
}
});
button.setText("Show Notification");
layout.addView(button);
}
setContentView(layout);
}
void showNotification() {
Intent intent = new Intent(this, getClass())
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Notification notification = new Notification.Builder(this)
.setContentTitle("Notification Example")
.setContentText("Notification example content.")
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setAutoCancel(true)
.build();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.notify(1, notification);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment