same application, different behaviors - java

I have problem with my app for Android.
When I run my app using Android studio, I start a servis (foreground) and it works.
But When I disconnect my device from computer, and run service, he doesnt work.
I run NotificationListenerService.
Someone knows what could be the cause of this ?
Please help
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
"abc.eu", "xyzabc", NotificationManager.IMPORTANCE_HIGH
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, "abc.eu")
.setContentTitle("title")
.setContentText("Content")
.setContentIntent(pendingIntent).build();
startForeground(1, notification);
packageManager = getPackageManager();
apps = loadData(apps);
Log.d("MainService", "onStartCommand");
return START_STICKY;
}

You may be didn't stop the previous Foreground Service from launching the app for the first time, so when you launch it for the second time, it doesn't start a new Foreground service until the first one is over.
So, first Make sure that your foreground service is stopped by calling stopForeground(true) followed by stopSelf()
Confirm that there is no notification in status bar related to your app.
If still you face a problem: add PendingIntent.FLAG_ONE_SHOT in the pending intent so that this PendingIntent can be used only once
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

Related

When your application is opened from notification is it possible to get back to previous application from where it was opened? Android

Is it possible to return to previous application from where your application is opened?
For example I am in application A then I click on notification and open my application B then in my application B I click a button and I get back to application A? Currently I am trying to do that and the only way how I achieved is when my application is running in background or it only works for the first time.
I am using Flutter but these actions are executed in native Android code so I am probably missing something.
For getting back to previous app I am using:
moveTaskToBack(true);
For creating a notification my code looks like this:
private void NotifyToAutofill(String uri, String url, NotificationManager notificationManager) {
if (notificationManager == null || isNullOrWhitespace(uri)) {
return;
}
Context context = getApplicationContext();
Intent startIntent = new Intent(context, MainActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startIntent.setAction(Intent.ACTION_RUN);
startIntent.putExtra("uri", uri);
startIntent.putExtra("url", url.contains("\u2022")
|| url.contains("\u2731") ? "" : url);
String channelId = "channel-01";
String channelName = "test";
int importance = NotificationManager.IMPORTANCE_LOW;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
int color = 0x008000;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Test Service")
.setContentText("Tap to open application")
.setAutoCancel(true);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(startIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(AutoFillNotificationId, notification);
}
Found the solution. My problem was that i was creating PendingIntent with
stackBuilder.addNextIntent(startIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Everything worked as intented when I used:
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Not able to clear notification and open fragment from notification

I am trying to clear notification. But it remains there. Not able to open fragment Activity from notification. Below is my code,
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int sticky;
try {
AndroidLogger.log(5, TAG, "Missed call notification on start");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
NotificationChannel channel = new NotificationChannel("1", "Call Notification", importance);
channel.setDescription("Get alert for missed call");
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Intent notifyIntent = new Intent(this, ViewFragment.class);
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
.setSmallIcon(R.drawable.nexge_logo)
.setContentTitle("Missed Call")
.setContentText(intent.getStringExtra("Number"))
.setContentIntent(pIntent)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX);
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//mNotifyMgr.notify(1, buildNotification);
startForeground(1,buildNotification);
} catch (Exception exception) {
AndroidLogger.error(1, TAG, "Exception while starting service", exception);
}
return START_NOT_STICKY;
}
}
Anybody help me to solve this. Thanks in Advance.
Below is my another question for which I didn't get a proper answer. Help me with that also
About Notification for Missed Call in android
My solution to a similar issue has been changing PendingIntent Flag to PendingIntent.FLAG_ONE_SHOT
From Android documentation:
Flag indicating that this PendingIntent can be used only once. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
and adding notification FLAG_AUTO_CANCEL flag:
mBuilder.flags |= Notification.FLAG_AUTO_CANCEL;
which should make sure the notification will be removed once used.
Edit:
Should call
Notification notification = mBuilder.build();
first, then
notification.flags = Notification.FLAG_AUTO_CANCEL;
Edit2:
Just noticed that you are using the notification for startForeground(). This means that the notification will stay for as long as your Service / Activity is running (this is by default so the user will know that there is a Service / Activity still running).
The notification will stay for as long as your Service / Activity does run as foreground service.

How can I launch wifi settings from a PendingIntent?

I'm trying to launch settings from a foreground service but getActivity() and getService() do nothing. Settings is never launched. Edit: here is how I'm setting the pending intent. The foreground service shows a plain notification with a line of clickable text
notificationBuilder.setOngoing(true)
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS));
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
notificationBuilder.addAction([mydrawable], "openSettings", pIntent);
This worked for me when I wanted to launch wifi settings on notification clicked.
val notificationBuilder = NotificationCompat.Builder(context, channelId).apply{setSmallIcon(R.drawable.icon)---<more code here>..
val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
setContentIntent(pendingIntent)}

Notification not showing when my alarm triggers onReceive() [duplicate]

This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I'm trying to pop up a notification when my alarm manager fires my onReceive() method. This is what I have done
#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(10000);
startNotification(context);
wl.release();
}
public void setAlarm(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(Activity, "MainActivity.class");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
assert am != null;
am.set(AlarmManager.RTC_WAKEUP, 60000, pi);
}
private void startNotification(Context context){
// Sets an ID for the notification
int mNotificationId = 001;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// Build Notification , setOngoing keeps the notification always in status bar
mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("RandomTitle")
.setContentText("RandomText")
.setOngoing(true);
// Create pending intent, mention the Activity which needs to be
//triggered when user clicks on notification(StopScript.class in this case)
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("extra","Extra Notificacion");
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
// context.startActivity(notificationIntent);
mBuilder.setContentIntent(contentIntent);
// Gets an instance of the NotificationManager service
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Android Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
// Builds the notification and issues it.
notificationManager.notify(mNotificationId, mBuilder.build());
}
Im really confused why this notification is not showing, I have tested my alarm and it triggers after 1 minute of beign created, but the notification is still not showing.
Any ideas?
thanks
From Android developer:
When you target Android 8.0 (API level 26), you must implement one or
more notification channels. If your targetSdkVersion is set to 25 or
lower, when your app runs on Android 8.0 (API level 26) or higher, it
behaves the same as it would on devices running Android 7.1 (API level
25) or lower.
Because your targetSdkVersion is 28, so you must add channelId in the Builder constructor too.
Change your code to:
// Build Notification , setOngoing keeps the notification always in status bar
mBuilder = new NotificationCompat.Builder(context, "notify_001") // Add channel ID to the constructor.
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("RandomTitle")
.setContentText("RandomText")
.setOngoing(true);
As per Android Developers Documentation :
NotificationCompat.Builder
NotificationCompat.Builder (Context context)
This constructor was deprecated in API level 26.1.0. use
NotificationCompat.Builder(Context, String) instead. All posted
Notifications must pecify a NotificationChannel Id.
Reference here
Edit:
Try the following :
Leave the NotificationCompat.Builder as it is now (with a string
representing NotificationChannel) .
Comment out your if block where you create a notification channel
Replace your NotificationManager with NotificationManagerCompat as the following :
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(mNotificationId, mBuilder.build());

Notification doesn't show all action buttons

I'm trying to create a simple notification for a music player that has 3 buttons, Pause, Previous and Next. My code only shows one of them which is Next. Any suggestions where I did a mistake?
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent playNextIntent = new Intent(this, BroadcastReceiver.class);
playNextIntent.setAction("NEXT_ACTION");
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 1, playNextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, BroadcastReceiver.class);
pauseIntent.setAction("PAUSE_ACTION");
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 2, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent playPreviousIntent = new Intent(this, BroadcastReceiver.class);
playPreviousIntent.setAction("PREVIOUS_ACTION");
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 3, playPreviousIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "D")
.setSmallIcon(R.drawable.ic_launcher_background) //notification icon
.setContentTitle("Simple Music Player")
.setContentText("Currently playing: " + mediaPlayerHolder.getSongsList().get(songIterator).getSongName())
.setPriority(NotificationCompat.PRIORITY_MAX)
.setWhen(0)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true) //user can't remove notification
.addAction(R.drawable.ic_previous, "Previous", prevPendingIntent) // #0
.addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) // #1
.addAction(R.drawable.ic_next, "Next", nextPendingIntent) // #2
.setStyle(new NotificationCompat.BigTextStyle())
.setContentIntent(pendingIntent); //on click go to app intent
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, mBuilder.build()); //show notification
There's nothing wrong with your code. If you run your code in an emulator on stock android the actions show up as expected.
On Android displaying notifications is done by the launcher. Like any other app launchers can contain bugs. In this case there is a bug in the launcher you're using to display multiple actions in a notification.
I recommend you to try a google sample Universal Music player Here is a GitHub link . It includes all of you want in notifications and it has a latest notification Android Oreo features just try out it .

Categories