How To Send Notification If The App Is At The Background In Android?
Currently I am working on bluetooth scan, that means I will keep scanning the device, if there is device nearby , I will show it on screen, however, if the app is at the background
Solution 1:
First you need to check if your application is in background.
You can call below code on onPause()
on every activity in your application:
/**
* Checks if the application is being sent in the background (i.e behind
* another application's Activity).
*
* @param context the context
* @return <code>true</code> if another application will be above this one.
*/publicstaticbooleanisApplicationSentToBackground(final Context context) {
ActivityManageram= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentNametopActivity= tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
returntrue;
}
}
returnfalse;
}
Add this line in your manifest file :
<uses-permissionandroid:name="android.permission.GET_TASKS" />
For adding notification you can add this code :
privatevoidaddNotification(Context context, String message) {
inticon= R.drawable.ic_launcher;
longwhen= System.currentTimeMillis();
Stringappname= context.getResources().getString(R.string.app_name);
NotificationManagernotificationManager= (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification;
PendingIntentcontentIntent= PendingIntent.getActivity(context, 0,
newIntent(context, myactivity.class), 0);
NotificationCompat.Builderbuilder=newNotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify(0 , notification);
}
Solution 2:
You can show notification from any of your Main or Service class. If you want to show notification from Main then use COntext in onReceive(Context context, Intent intent) method (context.getSystemService())
Try this code snippet :
NotificationManagermanager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notificationnotification=newNotification(R.drawable.ic_launcher,
"Hello from service", System.currentTimeMillis());
Intentintent=newIntent(this, MainActivity.class);
notification.setLatestEventInfo(this, "contentTitle", "contentText",
PendingIntent.getActivity(this, 1, intent, 0));
manager.notify(123, notification);
Post a Comment for "How To Send Notification If The App Is At The Background In Android?"