How to create notification - java

I want to create a simple notification in my app, but I can't. I searched for that, I read questions here and the google doc, but I don't know why it is not working. I watched that code from a video, but it doesnt work too.
private final String CHANNEL_ID = "personal_notifications";
private final int NOTIFICATION_ID = 001;
public void displayNotification(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID);
builder.setSmallIcon(R.drawable.power);
builder.setContentTitle("Noti");
builder.setContentText("mukodj mar");
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);

I use this code in a BroadcastReceiver:
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
StringBuilder sb = new StringBuilder();
NotificationCompat.BigTextStyle contentStyle = new NotificationCompat.BigTextStyle();
contentStyle.bigText((CharSequence) sb.toString());
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) // channel ID missing
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.icon)
.setStyle(contentStyle)
.setContentTitle("Title")
.setContentText(sb.toString())
.setAutoCancel(true);
notificationManager.notify(100, builder.build());
}
I think you forgot the last line:
notificationManager.notify(100, builder.build());

I got it. I made notification channel and its working now, anyway thanks guys!

Related

Android notification dont open activity?

I have an app that sends/receives notification using Firebase. Im sending the notification with no problem, but if the app is open the notification display an square instead of the smallicon also if i click the notification nothing happens, but if i'm using a different app i receive the notification and the notification show the correct icon and also opens the app.
public class MyMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void showNotification(String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifitcation")
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel =
new NotificationChannel("MyNotifitcation", "MyNotifitcation", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
FirebaseMessaging.getInstance().subscribeToTopic("general").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "Successfull";
if (!task.isSuccessful()) {
msg = "Failed";
}
// Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
For Notification click add Pending intent to notification builder. and for adding image/icon to notification use setSmallIcon() in notification builder. below is my notification code.
private void sendNotification(String body, String title) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("action_type", "notify");
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this,"channel")
.setSmallIcon(R.drawable.logo)
// .setContent(contentView)
.setContentTitle("title")
.setContentText("body")
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
See below code. Opening Activity.
original post credit
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

How to repeat android notifications after some Interval of hours

I am stuck with my app which needs to repeat one notification after one hour (Medical purpose). As my field is totally opposite and I am noob in coding any help will be appreciated. I know I have to add something in notification receiver to repeat notifications. But every time I try to repeat the app crashes.
(This is a little but unique idea to solve a real world problem I will credit everyone from whom I've received even a little help )
Here is my MainActivity
private NotificationManagerCompat manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = NotificationManagerCompat.from(this);
}
public void Shownotification(View v) {
String title = "You Did it!";
String message = "Some Text";
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
manager.notify(0,notification);
}
Notification Channel
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
Notification Reciever
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String title = "You Did it!";
String message = "Some Text";
Notification notification = new NotificationCompat.Builder(context, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
Intent i = new Intent("android.action.DISPLAY_NOTIFICATION");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
}
you can set new notification when previous one triggers.in onReceive Method of BroadcastReceiver.

Why is my Android notification not showing?

So, I'm developing an Android App and I need to send a notification of a certain event at a certain time.
However, for some reason the notification itself isn't showing up, despite the app not returning any errors or anything of the sort.
What could I possibly be doing wrong? This is my Receiver class.
The test print works properly so I don't think the connection to the receiver is the problem.
public class NotReceiver extends BroadcastReceiver{
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("test");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle("doge")
.setContentText("456")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
}
This is my Alarm function
#RequiresApi(api = Build.VERSION_CODES.O)
public void sendNotif(View view) {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
myIntent = new Intent(EventsActivity.this, NotReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
am.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+100, pendingIntent);
}

Repeating notification sound

Is it possible (and if yes how) to make push notification sound repeat until it's read? I am creating app that notifies user about new event in app, but user needs to read notification as soon as possible. When user "reads" notification it should stop ringing. Here's code:
public class GCMIntentService extends IntentService {
String mes;
HelperGlobals glob;
public GCMIntentService() {
super("GcmIntentService");
}
#SuppressLint("SimpleDateFormat")
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
glob = (HelperGlobals) getApplicationContext();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
// .... Doing work here
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
public void createPush(String title, String msg, Intent intent) {
Uri soundUri = Uri.parse("android.resource://example.project.com/" + R.raw.notification);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, DoNothing.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification n = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
n.defaults |= Notification.DEFAULT_VIBRATE;
//n.defaults |= Notification.DEFAULT_SOUND;
n.sound = soundUri;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
And BroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BukuLog", "Receiver");
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
like this:
Notification note = mBuilder.build();
//here
note.flags = Notification.FLAG_INSISTENT;
mNotificationManager.notify(1, note);
int FLAG_INSISTENT : Bit to be bitwise-ored into the flags field that if set, the audio will be repeated until the notification is cancelled or the notification window is opened.
follow android developer

Android Notification and NoSuchMethodError

I build a notification:
Notification.Builder builder = new Notification.Builder(
getApplicationContext())
.setTicker(
getApplicationContext().getString(
R.string.my_string))
.setSmallIcon(android.R.drawable.sym)
.setContentTitle(
getApplicationContext().getString(
R.string.my_string_two))
.setContentText(a.getB())
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] { 10001000 })
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0,
new Intent()
.setAction(Intent.ACTION_VIEW)
.setType(CallLog.Calls.CONTENT_TYPE)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
0));
NotificationManager nm = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify("interstitial_tag", 1, builder.build());
With android 4.0 i've found an error: NoSuchMethodError.
How can i solve it? Do i use Notification.Compact?
Thank you.
Can you try:
public static void sendNotification(Context context, String info){
NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(context);
//title notifications
notifyBuilder.setContentTitle(context.getString(R.string.app_name));
//small icon
notifyBuilder.setSmallIcon(R.drawable.ic_launcher);
//set contentText
notifyBuilder.setContentText(info);
notifyBuilder.setVibrate(new long[]{100, 200, 100, 500}); notifyBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
//setAutoCancel
notifyBuilder.setAutoCancel(true);
getNotificationManager(context).notify(0, notifyBuilder.build());
}
public final static NotificationManager getNotificationManager(Context context) {
return (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
And when you used a new Intent(), please insert a destination class
Intent wrapperIntent = new Intent(context, SenderBroadcast.class);
wrapperIntent.putExtra("KEY_UID", uid);
wrapperIntent.setData(Uri.parse("senderbroadcast://"+uid));
wrapperIntent.setAction("REQUESTCODE_SENDERBROADCAST");
PendingIntent.getActivity(context, RequestCode.REQUESTCODE_SENDERBROADCAST, wrapperIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Categories

Resources