I updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the activity based on the answer of CommonsWare:
Intent i = new Intent(context, AlarmNotificationActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // This is at least android 10...
Log.d("Debug", "This is android 10");
// Start the alert via full-screen intent.
PendingIntent startAlarmPendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String CHANNEL_ID = "my_channel_02";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.notification_channel_name_second),
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(startAlarmPendingIntent, true);
Log.d("Debug", "Try to load screen");
notificationManager.notify(0, builder.build());
}
The log shows that I am getting to the notify command but nothing happens. I am asking for USE_FULL_SCREEN_INTENT permission on the manifest so I should be able to use full-screen intents.
My app is useless now because of that issue. Does anyone know how to solve it?
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:
val pi = PendingIntent.getActivity(
appContext,
0,
Intent(appContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(pi, true)
val mgr = appContext.getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
mgr.createNotificationChannel(
NotificationChannel(
CHANNEL_WHATEVER,
"Whatever",
NotificationManager.IMPORTANCE_HIGH
)
)
}
mgr.notify(NOTIF_ID, builder.build())
You can use SYSTEM_ALERT_WINDOW to force launch activity window in android 10, refer to this settingsuperposition setting:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
in launched app check permissions:
private void RequestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
} else {
//Permission Granted-System will work
}
}
}
you will can user intent as android older versions
public class OnBootReceiver extends BroadcastReceiver {
private static final String TAG = OnBootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
try {
Intent activity = new Intent(context, MainActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
} catch (Exception e){
Log.d(TAG,e.getMessage()+"");
}
}
}
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
So you need to have a high-level notification and when the user clicks on the notification your activity will be opened notifications
public class UIExampleReceiver extends BroadcastReceiver {
public static final String TAG_NOTIFICATION = "NOTIFICATION_MESSAGE";
public static final String CHANNEL_ID = "channel_1111";
public static final int NOTIFICATION_ID = 111111;
private static final String TAG = "Receiver";
#Override
public void onReceive(Context context, Intent intent) {
try {
// If android 10 or higher
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P)
{
startActivityNotification(context,NOTIFICATION_ID,context.getResources().getString(R.string.open_app), context.getResources().getString(R.string.click_app));
}
else
{
// If lower than Android 10, we use the normal method ever.
Intent activity = new Intent(context, ExampleActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
}
} catch (Exception e)
{
Log.d(TAG,e.getMessage()+"");
}
}
// notification method to support opening activities on Android 10
public static void startActivityNotification(Context context, int notificationID,
String title, String message) {
NotificationManager mNotificationManager =
(NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Create GPSNotification builder
NotificationCompat.Builder mBuilder;
//Initialise ContentIntent
Intent ContentIntent = new Intent(context, ExampleActivity.class);
ContentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent ContentPendingIntent = PendingIntent.getActivity(context,
0,
ContentIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setColor(context.getResources().getColor(R.color.colorPrimaryDark))
.setAutoCancel(true)
.setContentIntent(ContentPendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
"Activity Opening Notification",
NotificationManager.IMPORTANCE_HIGH);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setDescription("Activity opening notification");
mBuilder.setChannelId(CHANNEL_ID);
Objects.requireNonNull(mNotificationManager).createNotificationChannel(mChannel);
}
Objects.requireNonNull(mNotificationManager).notify(TAG_NOTIFICATION,notificationID,
mBuilder.build());
}
}
Related
When push notification is received while the app is not running and the user presses on notification, it just disappears and the log says:
2019-10-22 12:42:45.747 23260-23260/de.app.test.staging E/FirebaseMessaging: Notification pending intent canceled
Here is the SplashActivity that is supposed to be launched as a Launcher Activity:
<activity
android:name="de.app.test.login.SplashActivity"
android:screenOrientation="portrait"
android:exported="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
What can the issue be here?
For anyone looking for an answer, the back-end was sending the "click_action" to notification, therefore there was no intent filter for that Activity.
For me the click_action is "OPEN_ACTIVITY_1" so I just added one more intent-filter to my SplashActivity like this:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
you need to set pendingIntent object in notificationBuilder instance like
mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
Intent intent = new Intent(context, TargetActivity.class));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
Please note that CHANNEL_ID is for build version greater or equal to Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CHANNEL_ID = createNotificationChannel(CHANNEL_ID, "channelName");
}
#RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(String channelId, String channelName) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
String description = "description";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
mNotificationManager.createNotificationChannel(channel);
return channelId;
}
Forground app:
You need a PendingIntent to open app.
Try this:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, SplashActivity.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);
If Activity is in background or closed then notification message is shown in the notification center for app launcher activity.
You can use a BroadcastReceiver class. When you close the app, broadcast can listen this action. So, if you create a BroadcastReceiver class, you don't take this problem.
public class ClosedBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, HomePage.class));
} else {
context.startService(new Intent(context, HomePage.class));
}
}
}
More Information:
https://firebase.google.com/docs/cloud-messaging/android/receive
I updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the activity based on the answer of CommonsWare:
Intent i = new Intent(context, AlarmNotificationActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // This is at least android 10...
Log.d("Debug", "This is android 10");
// Start the alert via full-screen intent.
PendingIntent startAlarmPendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String CHANNEL_ID = "my_channel_02";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.notification_channel_name_second),
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(startAlarmPendingIntent, true);
Log.d("Debug", "Try to load screen");
notificationManager.notify(0, builder.build());
}
The log shows that I am getting to the notify command but nothing happens. I am asking for USE_FULL_SCREEN_INTENT permission on the manifest so I should be able to use full-screen intents.
My app is useless now because of that issue. Does anyone know how to solve it?
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:
val pi = PendingIntent.getActivity(
appContext,
0,
Intent(appContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(pi, true)
val mgr = appContext.getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
mgr.createNotificationChannel(
NotificationChannel(
CHANNEL_WHATEVER,
"Whatever",
NotificationManager.IMPORTANCE_HIGH
)
)
}
mgr.notify(NOTIF_ID, builder.build())
You can use SYSTEM_ALERT_WINDOW to force launch activity window in android 10, refer to this settingsuperposition setting:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
in launched app check permissions:
private void RequestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
} else {
//Permission Granted-System will work
}
}
}
you will can user intent as android older versions
public class OnBootReceiver extends BroadcastReceiver {
private static final String TAG = OnBootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
try {
Intent activity = new Intent(context, MainActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
} catch (Exception e){
Log.d(TAG,e.getMessage()+"");
}
}
}
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
So you need to have a high-level notification and when the user clicks on the notification your activity will be opened notifications
public class UIExampleReceiver extends BroadcastReceiver {
public static final String TAG_NOTIFICATION = "NOTIFICATION_MESSAGE";
public static final String CHANNEL_ID = "channel_1111";
public static final int NOTIFICATION_ID = 111111;
private static final String TAG = "Receiver";
#Override
public void onReceive(Context context, Intent intent) {
try {
// If android 10 or higher
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P)
{
startActivityNotification(context,NOTIFICATION_ID,context.getResources().getString(R.string.open_app), context.getResources().getString(R.string.click_app));
}
else
{
// If lower than Android 10, we use the normal method ever.
Intent activity = new Intent(context, ExampleActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
}
} catch (Exception e)
{
Log.d(TAG,e.getMessage()+"");
}
}
// notification method to support opening activities on Android 10
public static void startActivityNotification(Context context, int notificationID,
String title, String message) {
NotificationManager mNotificationManager =
(NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Create GPSNotification builder
NotificationCompat.Builder mBuilder;
//Initialise ContentIntent
Intent ContentIntent = new Intent(context, ExampleActivity.class);
ContentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent ContentPendingIntent = PendingIntent.getActivity(context,
0,
ContentIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setColor(context.getResources().getColor(R.color.colorPrimaryDark))
.setAutoCancel(true)
.setContentIntent(ContentPendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
"Activity Opening Notification",
NotificationManager.IMPORTANCE_HIGH);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setDescription("Activity opening notification");
mBuilder.setChannelId(CHANNEL_ID);
Objects.requireNonNull(mNotificationManager).createNotificationChannel(mChannel);
}
Objects.requireNonNull(mNotificationManager).notify(TAG_NOTIFICATION,notificationID,
mBuilder.build());
}
}
I've got my local notifications running on androids prior to SDK 26
But in a Android O I've got the following warning, and the broadcast receiver is not fired.
W/BroadcastQueue: Background execution not allowed: receiving Intent { act=package.name.action.LOCAL_NOTIFICATION cat=[com.category.LocalNotification] flg=0x14 (has extras) } to package.name/com.category.localnotifications.LocalNotificationReceiver
From what I've read broadcast receivers are more restricted in android O, but if so, how should I schedule the broadcast if I want it launching even if the main activity is not running?
Should I use services instead of receivers?
This is the AlarmManager launch code:
public void Schedule(String aID, String aTitle, String aBody, int aNotificationCode, long aEpochTime)
{
Bundle lExtras = new Bundle();
lExtras.putInt("icon", f.getDefaultIcon());
lExtras.putString("title", aTitle);
lExtras.putString("message", aBody);
lExtras.putString("id", aID);
lExtras.putInt("requestcode", aNotificationCode);
Intent lIntent =
new Intent(LocalNotificationScheduler.ACTION_NAME)
.addCategory(NotificationsUtils.LocalNotifCategory)
.putExtras(lExtras);
PendingIntent lPendIntent = PendingIntent.getBroadcast(f.getApplicationContext(), aNotificationCode,
lIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager lAlarmMgr = (AlarmManager) f.getSystemService(Context.ALARM_SERVICE);
lAlarmMgr.set(AlarmManager.RTC, 1000, lPendIntent);
}
This is the receiver code:
public class LocalNotificationReceiver extends BroadcastReceiver {
public static native void nativeReceiveLocalNotification (String aID, String aTitle, String aMessage, boolean aOnForeground );
/** This method receives the alarms set by LocalNotificationScheduler,
* notifies the CAndroidNotifications c++ class, and (if needed) ships a notification banner
*/
#Override
public void onReceive(Context aContext, Intent aIntent)
{
Toast.makeText(context, text, duration).show();
}
}
Android manifest:
<receiver android:name="com.category.localnotifications.LocalNotificationReceiver">
<intent-filter>
<action android:name="${applicationId}.action.LOCAL_NOTIFICATION" />
<category android:name="com.category.LocalNotification" />
</intent-filter>
</receiver>
Android O are pretty new to-date. Hence, I try to digest and provide as accurate possible information.
From https://developer.android.com/about/versions/oreo/background.html#broadcasts
Apps that target Android 8.0 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest.
Apps can use Context.registerReceiver() at runtime to register a receiver for any broadcast, whether implicit or explicit.
Apps can continue to register explicit broadcasts in their manifest.
Also, in https://developer.android.com/training/scheduling/alarms.html , the examples are using explicit broadcast, and doesn't mention anything special regarding Android O.
May I suggest you try out explicit broadcast as follow?
public static void startAlarmBroadcastReceiver(Context context, long delay) {
Intent _intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Remove any previous pending intent.
alarmManager.cancel(pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pendingIntent);
}
AlarmBroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
In AndroidManifest, just define the class as
<receiver android:name="org.yccheok.AlarmBroadcastReceiver" >
</receiver>
Today i had the same problem and my notification was not working. I thought Alarm manager is not working in Oreo but the issue was with Notification. In Oreo we need to add Channel id. Please have a look into my new code:
int notifyID = 1;
String CHANNEL_ID = "your_name";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(HomeActivity.this)
.setContentTitle("Your title")
.setContentText("Your message")
.setSmallIcon(R.drawable.notification)
.setChannelId(CHANNEL_ID)
.build();
Check this solution. It worked like charm.
https://stackoverflow.com/a/43093261/4698320
I am showing my method:
public static void pendingListNotification(Context context, String totalCount) {
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.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationCompat.Builder mBuilder;
Intent notificationIntent = new Intent(context, HomeActivity.class);
Bundle bundle = new Bundle();
bundle.putString(AppConstant.PENDING_NOTIFICATION, AppConstant.TRUE);//PENDING_NOTIFICATION TRUE
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, importance);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder = new NotificationCompat.Builder(context)
// .setContentText("4")
.setSmallIcon(R.mipmap.logo)
.setPriority(Notification.PRIORITY_HIGH)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setContentTitle(context.getResources().getString(R.string.yankee));
} else {
mBuilder = new NotificationCompat.Builder(context)
// .setContentText("4")
.setSmallIcon(R.mipmap.logo)
.setPriority(Notification.PRIORITY_HIGH)
.setLights(Color.RED, 300, 300)
.setContentTitle(context.getResources().getString(R.string.yankee));
}
mBuilder.setContentIntent(contentIntent);
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mBuilder.setDefaults(defaults);
mBuilder.setContentText(context.getResources().getString(R.string.you_have) + " " + totalCount + " " + context.getResources().getString(R.string.new_pending_delivery));//You have new pending delivery.
mBuilder.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
Create the AlarmManager by defining an explicit intent (explicitly define the class name of the broadcast receiver):
private static PendingIntent getReminderReceiverIntent(Context context) {
Intent intent = new Intent("your_package_name.ReminderReceiver");
// create an explicit intent by defining a class
intent.setClass(context, ReminderReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
Also do not forget to create a notification channel for Android Oreo (API 26) when creating the actual notification:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (VERSION.SDK_INT >= VERSION_CODES.O) {
notificationManager.createNotificationChannel(NotificationFactory.createNotificationChannel(context));
} else {
notificationManager.notify(NotificationsHelper.NOTIFICATION_ID_REMINDER, notificationBuilder.build());
}
try this code for android O 8.1
Intent nIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
nIntent.addCategory("android.intent.category.DEFAULT");
nIntent.putExtra("message", "test");
nIntent.setClass(this, AlarmReceiver.class);
PendingIntent broadcast = PendingIntent.getBroadcast(getAppContext(), 100, nIntent, PendingIntent.FLAG_UPDATE_CURRENT);
I made apps that need to get a notification though the apps are closed. I'm using fcm to get the notification. But when the apps are removed from the recent task, I stop getting a notification. I had seen other article but I still can't get the answer to my problem.
I'm using firebase:
'com.google.firebase:firebase-messaging:11.0.2'
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
Log.e(TAG," remote :" +remoteMessage.toString() );
try {
JSONObject json = new JSONObject(remoteMessage.getData());
String title = json.get("title").toString();
String message = json.get("message").toString();
createNottification(title, message);
}
catch (Exception ex){}
if(remoteMessage.getNotification() != null)
Log.d(TAG, "Message Notification Body: "+remoteMessage.getNotification().getBody());
}
private void createNottification(String title,String message)
{
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);;
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.pmi_launcher)
.setSound(notificationSoundURI )
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(Config.NOTIFICATION_ID, notification);
}
}
Manifest.xml
<!-- Firebase Notifications -->
<service android:name=".services.MyFirebaseMessagingService" android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".services.MyFirebaseInstanceIDService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
first pass PendingIntent and also pass unique notification ID for generate bunch or stack of notification. also set Flags for notification Intent.so just do this in this way. Hope it helps to you and also other users.
private void sendNotification(String message,String title) {
int id = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(this, SplashActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
//.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image).setSummaryText(message))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
} else {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
}
I'm making a gcm application, and now I can receive the notification
But when I click the notification, it just open the app.
I need to open another activity instead of Mainactivity
is there any way to do this?
final Intent intent = new Intent(context, YourActivity.class);
intent.putExtra("key", "value");
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.set...;
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Please read this for detail about creating a Notification http://developer.android.com/guide/topics/ui/notifiers/notifications.html.
Depend on http://developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse, there are two general situations of starting Activity from your notification – Regular activity and Special activity.
Methods below are the example of start 2 type of Activity:
Regular activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = null;
ComponentName componentName = intent.getComponent();
if (componentName != null) {
// 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(this);
// Adds the back stack for the Intent (but not the Intent itself) <== This comment must be wrong!
stackBuilder.addParentStack(componentName);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
resultPendingIntent = stackBuilder.getPendingIntent(REQUEST_CODE_START_ACTIVITY, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
} else {
resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
}
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Usage :
Intent intent = new Intent(this, SignInActivity_.class);
sendNotification(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title, message, intent);
The manifest XML should look like this
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignInActivity_"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
Special activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Note:
Because I use setDefaults(DEFAULT_ALL), the vibrate permission is require <uses-permission android:name="android.permission.VIBRATE" />
Yes, it's possible. You must set the "exported" flag of the activity in the manifest.xml to true.
Hope it helps.
Use this:
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent=new Intent(context,YourActivity.class);
PendingIntent pending=PendingIntent.getActivity(context, 0, intent, 0);
Notification notification;
if (Build.VERSION.SDK_INT < 11) {
notification = new Notification(icon, "Title", when);
notification.setLatestEventInfo(
context,
"Title",
"Text",
pending);
} else {
notification = new Notification.Builder(context)
.setContentTitle("Title")
.setContentText(
"Text").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pending).setWhen(when).setAutoCancel(true)
.build();
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
nm.notify(0, notification);