I need to make my app open after clicking on the notification “App is running in the background”, but when I clicked it open the App Infos, how can I avoid this and open the app itself.
Here is the code that I using to show this notification:
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationChannel channel = new NotificationChannel("Player", "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(this, "Player")
.setContentTitle("Music Player")
.setContentText("My Music")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setOngoing(true);
Notification notification = builder.build();
startForeground(1, notification);
Obs. this app really uses a background service and I don't want to hide this notification.
Try this one.
package developer.eyosiyas.NileSat.Habesha.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import developer.eyosiyas.NileSat.Habesha.R;
import developer.eyosiyas.NileSat.Habesha.View.MainActivity;
public class ServiceExample extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationManager notificationManager;
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("Player", "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(R.color.colorPrimary);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setDescription("Service Name");
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Player")
.setContentTitle("Music Player")
.setContentText("My Music")
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setOngoing(true);
Notification notification = builder.build();
notificationManager.notify(1, notification);
startForeground(1, notification);
}
}
Related
I set the alarm for the next day, when the time comes nothing happens. The notification is not being shown, but if I open the application; the notification show up. What can I do? Here is my code.
The documentation: https://developer.android.com/develop/ui/views/notifications/build-notification#java
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
public class AlarmReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "SAMPLE_CHANNEL";
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId",0);
String message = intent.getStringExtra("todo");
Intent mainIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,0,mainIntent,0);
NotificationManager myNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence channel_name = "My Notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channel_name, importance);
myNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("It's Time!")
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
myNotificationManager.notify(notificationId, builder.build());
}
}
I need a button in my Notification, however everything i find online is not working. I need it to cancel playing an alarm that will go off at a designated time. Can anyone link me some articles to read or tell me what code i should use in order to get this to work.
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import com.example.oceansscheduler.MainActivity;
import com.example.oceansscheduler.R;
public class AlarmReceiver extends BroadcastReceiver {
public void showNotification(Context context, String title, String message, Intent intent, int reqCode) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, reqCode, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_name";// The id of the channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_alarm_24)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle())
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentText(message)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel Name";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(reqCode, notificationBuilder.build()); // 0 is the request code, it should be unique id
Log.d("showNotification", "showNotification: " + reqCode);
}
#Override
public void onReceive(Context context, Intent intent) {
SQLiteDatabase db = context.openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);
Log.d("Count", String.valueOf(data.getCount()));
if (data.getCount() > 0) {
data.moveToFirst();
String NameOfNotif = (data.getString(0));
Toast.makeText(context, NameOfNotif, Toast.LENGTH_LONG).show();
int reqCode = 1;
Intent intentNotif = new Intent(context, MainActivity.class);
showNotification(context, NameOfNotif, "Your Reminder is going off!", intentNotif, reqCode);
}
}
};
To add a button in Your notification, You need to use addAction function.
It requires an Action object which needs:
an icon (oddly),
a title,
a PendingIntent
The PendingItent can encapuslate an Intent that can be a Service that will be delegated to cancel playing the alarm or a Receiver that will do it.
Let's stick with a receiver. We can create one - CancelAlarmReceiver:
public class CancelAlarmReceiver extends BroadcastReceiver {
public static String ACTION_CANCEL = "actionCancelAlarm";
public CancelAlarmReceiver() {}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_CANCEL)) {
// Here You will cancel the alarm.
}
}
}
Remember to register it in the Manifest:
<receiver
android:name=".CancelAlarmReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.your.app.CancelAlarmReceiver.ACTION_CANCEL" />
</intent-filter>
</receiver>
Later on, when creating a notification with a builder, You will have to provide an action leading to our Receiver:
Intent cancelIntent = new Intent(this, CancelAlarmReceiver.class);
cancelIntent.setAction(ACTION_CANCEL);
PendingIntent cancelPendingIntent =
PendingIntent.getBroadcast(this, NOTIFICATION_ID,
cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(
new Notification.Action(
R.drawable.ic_alarm_cancel,
getString(R.string.cancel_alarm),
cancelPendingIntent
)
);
This should make sure that a button will appear by Your notification and it will trigger the receiver and disable the alarm (or whatever You will make it to do).
im trying to send notification to phone, but it doesnt send
imports:
import androidx.core.app.NotificationCompat;
import android.content.Context;
import android.app.NotificationManager;
my code:
public void sendNotification(){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationChannel.DEFAULT_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Title")
.setContentText("Content");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
}
Why isn't it showing?
Is intent needed?
What should the channel be?
Thanks!
If you are using a Service
Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, 100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel =
new NotificationChannel(
100,
"Media PlayBack",
NotificationManager.IMPORTANCE_LOW);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Title")
.setContentText("Content")
.setContentIntent(contentIntent);
Notification notification = builder.build();
startForeground(101, notification);
If you're using firebase to send notifications you need a firebase messaging service activity to receive the notifications. and add the data to your manifest file to receive notifications.
I am trying to add a notification feature to my application. I want it to run a notification or action at the same time, every day. I have this code for my notification right now:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 45612;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
// Build the notification
notification.setSmallIcon(R.drawable.icon);
notification.setTicker("Brook Betterment Plan");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Brook Betterment Plan");
notification.setContentText("Don't forget to enter your daily stats! ");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
// Builds notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
}
Thanks! Hope someone knows the answer. Also, I was hoping it wouldn't need any additional Activitys or Java class's.
Alarm Manager
public static void startAlarmBroadcastReceiver(Context context) {
Intent _intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Alarm Broadcast Receiver
In AndroidManifest, just define the class as
<receiver android:name=".AlarmBroadcastReceiver" >
</receiver>
And code will be like
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
void showNotification(Context context) {
String CHANNEL_ID = "your_name";// The id of the channel.
CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
NotificationCompat.Builder mBuilder;
Intent notificationIntent = new Intent(context, TestActivity.class);
Bundle bundle = new Bundle();
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setContentTitle("Title");
} else {
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(Notification.PRIORITY_HIGH)
.setContentTitle("Title");
}
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("Your Text");
mBuilder.setAutoCancel(true);
mNotificationManager.notify(1, mBuilder.build());
}
}
Create a class that will generate notification, like LocalNotification
Add the code you have in on create in that class under a method like showDailyNotification
Now use JobScheduler and schedule a job for every 24 hours, when the job is started call this method in LocalNotification
Make LocalNotification a singleton class.
BTW don't forget to use notification channel because otherwise it will not work on Oreo and above devices.
I am getting "The method getSystemService(String) is undefined for the type AlarmManagerBroadcastReceiver" error. I even tried to put getActivity() before it but it was of no help.
code for AlarmManagerBroadcastReceiver.java
package com.archana.pocketfriendly;
import java.text.Format;
import java.text.SimpleDateFormat;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
MediaPlayer alarm;
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();
//You can do the processing here update the widget/remote views.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
alarm = MediaPlayer.create(context, R.raw.alarm);
alarm.start();
msgStr.append("Do you want to enter the expenses?\nIgnore if already done!");
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
Vibrator vib=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(2000);
// notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.settings)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainMenu.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainMenu.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //error in this `enter code here`line.
mNotificationManager.notify(0, mBuilder.build());
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 86400 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Please let me know if any other information is required.
Just like your other calls to getSystemService, you need to perform it on a context object:
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);