Notification not showing up when I close the app - java

So I made some code that makes the app show up at the time specified. It works well enough when the app is open on the screen, but when it is closed, it doesn't work at all. I need help making it show up.
Code for MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initChannels(this);
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 00);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
Code for MyReceiver.java which extends BroadcastReceiver:
public MyReceiver() {
}
#Override
public void onReceive(Context context,Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
Code for MyNewIntentService which extends IntentService:
private static final int notificationId = 4242;
public MyNewIntentService() {
super("MyNewIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
//NOTIFICATION CREATION
// Create an explicit intent for an Activity in your app
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "default")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("This is the title")
.setContentText("This is the body of the notification.")
.setVisibility(VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, mBuilder.build());
}
And I added this in the AndroidManifest.xml:
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false" >
</receiver>
<service
android:name=".MyNewIntentService"
android:exported="false" >
</service>
I know there's a lot of text in this question and I apologize for that, but I think that'll make it easier for you to help me or see what the problem is.

try this
firebase notification are two types:
data message: when your app background/foreground/killed your push notification is worked
display message: when your app foreground push notification works
Handle push notification these stages background/foreground/killed
it depends your json response make sure your json response like this:
{
"to": "registration_ids",
"data": {
"key": "value",
"key": "value",
"key": "value",
"key": "value"
}
}
this is my code when your app background/foreground/killed it works fine
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "remoteMessage......" + remoteMessage.getData());
try {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Log.e(TAG, object.toString());
body = object.getString("not_id");
dataa = object.getString("data");
title = object.getString("not_type");
type = object.getString("type");
Sender = object.getString("Sender");
SenderProfileUrl = object.getString("SenderProfileUrl");
wakeUpScreen();
addNotification(remoteMessage.getData());
}
/* when your phone is locked screen wakeup method*/
private void wakeUpScreen() {
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
Log.e("screen on......", "" + isScreenOn);
if (isScreenOn == false) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
wl.acquire(10000);
PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
wl_cpu.acquire(10000);
}
}
/*Add notification method use for add icon and title*/
private void addNotification(Map<String, String> data) {
int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?R.drawable.logo_app: R.drawable.logo_app;
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(icon)
//.setSmallIcon(R.drawable.logout_icon)
.setContentTitle(data.get("title") + "")
.setChannelId("channel-01")
.setAutoCancel(true)
.setSound(uri)
.setContentText(data.get("body") + "");
Notification notification = new Notification();
Log.e(TAG, "titlee" + data.get("title"));
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if (sound)
notification.defaults |= Notification.DEFAULT_SOUND;
if (vibration)
notification.defaults |= Notification.DEFAULT_VIBRATE;
builder.setDefaults(notification.defaults);
}
}
when i click notification bar goto the particular screen using type like this:
/*notification send with type calling */
if (data.get("not_type").equals("calling")) {
if (data.get("type").equals("name")) {
Log.e(TAG, "ttt--" + type);
Intent notificationIntent = new Intent(this, CallingActivity.class);
notificationIntent.putExtra("notification_room_id", body);
notificationIntent.putExtra("data", dataa);
notificationIntent.putExtra("calling", "calling");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setSound(uri);
builder.setAutoCancel(true);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Hello";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel("channel-01", name, importance);
manager.createNotificationChannel(mChannel);
}
manager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), builder.build());
}
this is my manifest add notification class and token class
<service android:name=".notification.NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".notification.TokenService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".notification.NLService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
i hope it helps you

Related

Android studio notifications implemented but not showing

I have implemented android notifications in android studio. I was creating notification for a media player. following is the function for showing notifications
public void showNotification(int playPauseBtn)
{
Intent intent = new Intent(this, PlayerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
try
{
picture = getAlbumArt(listSongs.get(position).getPath());
} catch (Exception ignored)
{
}
Bitmap thumb;
if (picture != null)
{
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
} else
{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.icon_music);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_1).setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(listSongs.get(position).getTitle())
.setContentText(listSongs.get(position).getArtist())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPending)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPending)
.addAction(playPauseBtn, "pause", pausePending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
Toast.makeText(PlayerActivity.this, "Nitification created", Toast.LENGTH_SHORT).show();
}
In the function parameter (playPauseBtn) I am sending the play icon or the pause icon depending upon weather the song is playing or is paused.
Function call is made like following:
showNotification(R.drawable.ic_baseline_pause_24);
OR
showNotification(R.drawable.ic_baseline_play_arrow_24);
But when ever I call this function the notification doesn't show up. I am also using the notification channel but still it is not working. I have also tried to debug the code but the code runs fine, still the notification doesn't show up. please advise
try this.
put this code in your Activity/fragment;
public void getNotification(){
int notifId =new Random().nextInt(500); //get random id
NotificationManager notificationManager;
Notification notification;
notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelID = "1";
channelName = "news";
channelDesc = "news description";
NotificationChannel notificationChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(channelDesc);
notificationChannel.enableLights(true);
notificationChannel.setSound(null, null);
notificationChannel.setLightColor(Color.GREEN);
notificationManager.createNotificationChannel(notificationChannel);
}
RingtoneManager.getRingtone(mContext,
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).play();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title Of MUSIC")
.setContentText("Content")
.setVibrate(new long[]{100, 500, 500, 500, 500})
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
Intent actionReadMessage = new Intent(mContext, NotifAction.class);
actionReadMessage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
actionReadMessage.setAction("Play");
actionReadMessage.putExtra("NotifId",notifId);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(mContext, notifId, actionReadMessage,PendingIntent.FLAG_CANCEL_CURRENT);
Intent mainAction = new Intent(mContext, NotifAction.class);
mainAction.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAction.setAction("Pause");
mainAction.putExtra("NotifId",notifId);
PendingIntent PausePendingIntent = PendingIntent.getBroadcast(mContext, notifId, mainAction,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(PausePendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Play", playPendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Pause", PausePendingIntent);
notification = builder.build();
notificationManager.notify(notifId, notification);
}
and create class NotifAction.class for handle all action:
public class NotifAction extends BroadcastReceiver {
private static final String TAG = "maybe";
private MediaPlayer mp;
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Bundle extra = intent.getExtras();
if (extra != null) {
int notifId = extra.getInt("NotifId");
if (action.equals("Play")) {
mp = MediaPlayer.create(context, R.raw.music);
handleMusicState(mp);
} else if (action.equals("Pause")) {
handleMusicState(mp);
setMessageRead(notifId, context);
} else {
Toast.makeText(context, "extra action !", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Empty extra !", Toast.LENGTH_SHORT).show();
}
}
private void setMessageRead(int id, Context context) {
// other method
clearNotification(id, context);
}
private void clearNotification(int id, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
private void handleMusicState(MediaPlayer mediaPlayer) {
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
else mediaPlayer.start();
}
}
define this receiver to manifest:
note:in tag
<receiver android:name=".NotifAction">
<intent-filter>
<action android:name="Play" />
<action android:name="Pause" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
FIX
Donot use .setMediaSession(mediaSessionCompat.getSessionToken()) in .setStyle() in the code given in the question
simply just use
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle())

Unique Notifications at Unique Times with broadcastReceiver

i am currently devoloping small app and i struggle about sending notifications.
My Goal: I have different tasks and they need to send unique notifications at unique time to user even
while app is closed.
What I did?: I did create different broadCastReceiver's to make them work in harmony with
alarmManager' s but even i changed the request code , flag or channel code, i do get notifications at
same time if user enables notifications for more than one task, but alarmManagers for notifications
are not supposed to work after same time.
'receiver' part of AndroidManifest.xml
<receiver
android:name=".BroadcastReceiver"
android:exported="true">
<intent-filter>
<action
android:name="pendingIntent">
</action>
</intent-filter>
</receiver>
<receiver
android:name=".BroadcastReceiver2"
android:exported="true">
<intent-filter>
<action
android:name="pendingIntent2">
</action>
</intent-filter>
</receiver>
first and second broadCastReceiver
public class BroadcastReceiver extends android.content.BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "100")
.setSmallIcon(R.drawable.logologo)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(100, builder.build());
}
}
}
public class BroadcastReceiver2 extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"102")
.setSmallIcon(R.drawable.logologo)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(102, builder.build());
}
}
First and second Channel
public void createChannel1()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "channel1";
String description = "channel1 description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel1 = new NotificationChannel("100", name, importance);
channel1.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel1);
}
}
public void createChannel2()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "channel2";
String description = "channel2 description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel2 = new NotificationChannel("102", name,importance);
channel2.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel2);
}
}
Activity that needed to send Notification from first broadCastReceiver on Channel1 and
Activity that needed to send Notification from second broadCastReceiver on Channel2
button30.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(SmokeActivity.this, BroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(SmokeActivity.this, 100, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60, pendingIntent);
}
});
button29.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(WaterActivity.this, "Notifications Set", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(WaterActivity.this, BroadcastReceiver2.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(WaterActivity.this,0,intent2,0);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
// Set the alarm to start at 8:30 a.m.
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(System.currentTimeMillis());
calendar2.set(Calendar.HOUR_OF_DAY, 8);
calendar2.set(Calendar.MINUTE, 30);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),
1000*45, pendingIntent2);
}
});
For anyone suffering from same problem, the thing is android system does not allow us to send notification after first 10 minute when you create notification.

My receiver is not showing notification - why? [duplicate]

This question already has answers here:
Android notification is not showing
(14 answers)
Closed 4 years ago.
//I had given intent in oncreate
Intent alarmIntent = new Intent(getContext(), ServiceReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getContext(),
0, alarmIntent, 0);
// here i am setting alarm
public void setALARM(String time, String strDate){
AlarmManager manager = (AlarmManager) getContext()
.getSystemService(Context.ALARM_SERVICE);
String strHour=formateDateFromstring("HH:mm","HH",time);
String strMin=formateDateFromstring("HH:mm","mm",time);
String strdate=formateDateFromstring("yyyy-MM-dd","dd",strDate);
String strMonth=formateDateFromstring("yyyy-MM-dd","MM",strDate);
String strYear=formateDateFromstring("yyyy-MM-dd","yyyy",strDate);
int hour=Integer.parseInt(strHour);
int min=Integer.parseInt(strMin);
int date=Integer.parseInt(strdate);
int month=Integer.parseInt(strMonth)-1;
int year=Integer.parseInt(strYear);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH,date); //1-31
cal.set(Calendar.MONTH,month); //first month is 0!!! January is zero!!!
cal.set(Calendar.YEAR,year);//year...
cal.set(Calendar.HOUR_OF_DAY,hour); //HOUR
cal.set(Calendar.MINUTE,min);//MIN
cal.set(Calendar.SECOND,0);
manager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
}
//Here is my receiver class
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logob_icon_prestigesalon)
.setContentTitle("ABC")
.setContentText("time to go")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Toast.makeText(context,"service",Toast.LENGTH_LONG).show();
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationmanager.notify(0, builder.build());
}
}
//I mentioned receiver class in manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".ServiceReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<!-- Will not be called unless the application explicitly enables it -->
<receiver android:name=".DeviceBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
I want to set an alarm for the exact time.I checked the code in debug mode whether the debug is coming inside the onReceive if the given time comes.The debug is coming whe the given time is reached.The issue is notification is not visible.
Not sure if it is your specific problem, but NotificationCompat.Builder(Context context) is deprecated in API level 26.1.0. You should use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id for 26+ devices as you can check in Notification and Notification.Builder documentation
Try something like this,Have not tested.
String channelID = "Notification_Channel_ID";
String channelDesr = "Notification_channel_description";
buildNotificationChannel(channelID,channelDesr);
public void buildNotificationChannel(String channelID, String description) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager.getNotificationChannel(channelID) == null) {
NotificationChannel channel = new NotificationChannel(channelID, description,
NotificationManager.IMPORTANCE_LOW);
channel.setDescription(description);
manager.createNotificationChannel(channel);
}
}
}
NotificationCompat.Builder builder = new
NotificationCompat.Builder(context,channelID)
.setSmallIcon(R.drawable.logob_icon_prestigesalon)
.setContentTitle("ABC")
.setContentText("time to go")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Toast.makeText(context,"service",Toast.LENGTH_LONG).show();
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationmanager.notify(0, builder.build());

Android notification not able to access the received string

I receive a notification in broadcast receiver like this in MainActivity.java. I need to access this string textMessage for my other classes -
if (intent.getAction().equals("NOTIFY_TEXT_MESSAGE")){
String textMessage = intent.getStringExtra("TextMessage");
Intent noti_intent = new Intent(MainActivity.this, NotificationReceiver.class);
noti_intent.setAction("NotificationReceived");
noti_intent.putExtra("NotificationMessage",textMessage);
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, noti_intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.text_messages)
.setContentTitle(getResources().getString(R.string.Message_Title))
.setContentText(textMessage)
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
.addAction(0,
getString(R.string.Open), pi)
.setAutoCancel(true);
builder.setSound(soundUri);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
In NotificationReceiver.class,
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("NotificationReceived".equals(action)) {
String msg = MainActivity.NotificationMessage;
Log.v("shuffTest","msg" + msg);
}
}
}
In my Manifest,
<receiver android:name="com.example.NotificationReceiver">
<intent-filter>
<action android:name="NotificationReceived" />
</intent-filter>
</receiver>
Why the log msg is not appearing. What is the mistake in my code?
Try to get the message from the intent, like this:
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("NotificationReceived".equals(action)) {
String msg = intent.getStringExtra("NotificationMessage");
Log.v("shuffTest","msg" + msg);
}
}
}

How to start activity when user clicks a notification?

I am attempting to convert some code I found in a tutorial for my own use. Originally, the code launched the system contacts list when the user would click a notification generated by my app. I am trying to start an Activity of my own instead of launching the contact list, but it's not working. More specifically, nothing happens. There is no error, and my Activity doesn't load either. The notification window disappears after clicking, and the original Activity is still visible.
Here is my code:
public class MyBroadcastReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
public void onReceive(Context context, Intent intent){
Bundle extras = intent.getExtras();
String deal = (String) extras.get("Deal");
String title = "Deal found at " + (String) extras.get("LocationName");
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notifyDetails = new Notification(R.drawable.icon, title,System.currentTimeMillis());
Class ourClass;
try {
ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget");
Intent startMyActivity = new Intent(context, ourClass);
PendingIntent myIntent = PendingIntent.getActivity(context, 0,startMyActivity, 0);
notifyDetails.setLatestEventInfo(context, title, deal, myIntent);
notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
notifyDetails.flags |= Notification.DEFAULT_SOUND;
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
This is my entry in the AndroidManifext.xml file...
<activity android:name=".ViewTarget" android:label="#string/app_name" >
<intent-filter>
<action android:name="com.kjdv.gpsVegas.ViewTarget" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And this is my Activity that I want to launch...
public class ViewTarget extends ListActivity {
public ListAdapter getListAdapter() {
return super.getListAdapter();
}
public ListView getListView() {
return super.getListView();
}
public void setListAdapter(ListAdapter adapter) {
super.setListAdapter(adapter);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locations);
Log.v("db", "Inside ViewTarget");
}
}
Which Android version are you running on? You might wanna try using NotificationCompat instead. This class is include in the latest support package.
Intent notificationIntent = new Intent(context, ViewTarget.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = context.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.app_icon)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.app_icon))
.setTicker(payload)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("Message")
.setContentText(payload);
Notification n = builder.getNotification();
n.defaults |= Notification.DEFAULT_ALL;
nm.notify(0, n);
EDIT:
I know this is an old thread/question but this answer helped me for showing the activity when tapping the notification.
For those people that this isn't working is probably because you haven't "registered" the activity in your manifest. For example:
<activity
android:name="com.package.name.NameOfActivityToLaunch"
android:label="Title of Activity" >
<intent-filter>
<action android:name="com.package.name.NAMEOFACTIVITYTOLAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And, hopefully, this should work.
Hope it helped...
you should set action and category for Intent.
Intent startMyActivity = new Intent(context, ourClass);
startMyActivity .setAction(Intent.ACTION_MAIN);
startMyActivity .addCategory(Intent.CATEGORY_LAUNCHER);
it works
I figured out the problem. I forgot to include the package name in the activity declaration in the Manifest file.
Wrong:
activity android:name=".ViewTarget" android:label="#string/app_name"
Correct:
activity android:name="com.kjdv.gpsVegas.ViewTarget" android:label="#string/app_name"
Can you try removing the Intent filter, so it looks like this:
<activity android:name=".ViewTarget" android:label="#string/app_name" />
Also, not sure if this code will work:
ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget");
Intent startMyActivity = new Intent(context, ourClass);
Can you try it like this instead:
Intent startMyActivity = new Intent(context, ViewTarget.class);
In order to launch an Activity from an Intent, you need to add a flag:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is true even if you declare the class in the Intent's constructor.
check this code
public class TestActivity extends Activity {
private static final int UNIQUE_ID = 882;
public static NotificationManager nm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent navigationIntent = new Intent();
navigationIntent.setClass(classname.this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, navigationIntent,
0);
String body = "New notificattion added!!!";
String title = "Notification";
Notification n = new Notification(R.drawable.icon, body,
System.currentTimeMillis());
//this is for giving number on the notification icon
n.number = Integer.parseInt(responseText);
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(UNIQUE_ID, n);

Categories

Resources