notification button not working - android

i m creating custoom notification in my app.the notification shows up,but when i click on button,the button doesnt work.i dont know what to do.i looked in all the answer on stackoverflow but didnt get the idea.so,please help me.
this is code for notification
private void customNotification() {
Intent closeButton = new Intent("Download_Cancelled");
closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(getContext(), 0, closeButton, 0);
RemoteViews notificationView = new RemoteViews(getContext().getPackageName(), R.layout.notification);
NotificationManager notificationManager = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
.setSmallIcon(R.drawable.music)
.setContent(notificationView)
.setChannelId(ID);
notificationView.setOnClickPendingIntent(R.id.next, pendingSwitchIntent);
notificationManager.notify(0, builder.build());
}
this is broadcast activity
public class NotificationBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"thanks",Toast.LENGTH_LONG).show();
}
}
this is manifest
<receiver android:name=".BlankFragment2$NotificationBroadcast">
<intent-filter>
<action android:name="Download_Cancelled" />
</intent-filter>
</receiver>

Related

BroadcastReceiver not firing from NotificationManager

I have the following code:
public void sendNotification() {
try {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
final Intent intent = new Intent(this, NotifyBroadcastReceiver.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
builder.setAutoCancel(true);
final Intent noted = new Intent(this, NotifyBroadcastReceiver.class);
noted.setAction("com.mawaeed.common.LaunchActivity");
PendingIntent notedpendingIntent = PendingIntent.getBroadcast(this, 0, noted, 0);// PendingIntent.FLAG_UPDATE_CURRENT ) ;
builder.addAction(0, "Noted", notedpendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}catch(Exception exo) {
Toast.makeText(this, exo.toString(),Toast.LENGTH_LONG).show();
}
}
Also I have my BroadcastReceiver
public class NotifyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"ddd",Toast.LENGTH_LONG).show();
Toast.makeText(context,"app",Toast.LENGTH_LONG).show();
}}
I am calling sendNotification from FirebaseMessagingService, Notification appears normally.
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification();
}
When clicking on the notification or Noted action, BroadcastReceiver onReceive not calling,
I already registered my BroadcastReceiver in mainafist
<receiver android:name=".NotifyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>
The strange thing is I created a new application and copied all the code above to it, and I called the sendNotification from onCreate(), and when clicking on the notification it calls onReceive without problem.
I also tried same with my Application and called sendNotification from onCreate of my main activity, Notification appears but clicking on notification or Noted action not calling onReceive
Why it is not working from my application
I had to uninstall the app first then install it again, and now it works.

How to show status bar notification at a later time?

I've successfully created a status bar notification but I want it to pop up 6 hours after the user exits the app.
I have the following code:
public class myClass extends superClass implements myinterface {
final int NOTIF_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {.........}
/* more methods etc */ ......
#Override
protected void onDestroy() {
View iop = (View) findViewById(R.id.app);
sendNotification(iop);
super.onDestroy();
}
public void sendNotification(View view) {
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.drawable.ic_launcher);
// This intent is fired when notification is clicked
Intent intent = new Intent(view.getContext(), AndroidLauncher.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Notifications Title");
// Content text, which appears in smaller text below the title
builder.setContentText("Your notification content here.");
// The subtext, which appears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText("Tap to view documentation about notifications.");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(NOTIF_ID, builder.build());
}
A status bar notification pops up when the app is exited but I want it to popup after 6 hours since the time user exits the app. How do I go about it?
Thanks in advance!
You can use an AlarmManager to schedule a broadcast that contains your notification.
private void scheduleNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
builder.setSmallIcon(R.drawable.ic_launcher);]
Notification notification = builder.build();
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(6);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then use a BroadcastReceiver to receive the intent and show the notification.
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Don't forget to register the receiver in your AndroidManifest.xml file.
(Source: https://gist.github.com/BrandonSmith/6679223)
create a new class which will execute the alarm using pending intent and alarm manager.
long time= 6*60*60*1000; //6 hours
new Alarm_task(this, time).run();
public class Alarm_task implements Runnable{
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
long alarm_time;
public Alarm_task(Context context, long time) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.alarm_time = time;
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
//pop up a notification into the system bar not a full activity
Intent i = new Intent("intent name");
// can create a dialog in that intent or just call the sendNotification() function
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + alarm_time, operation);
}
}
define intent in your manifest file:
<activity
android:name=".Activity name"
android:label="#string/app_name" >
<intent-filter>
<action android:name="Intent name" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
now in that activity you can call Sendnotification() function during onCreate().. or show some UI according to your application
call this method from onDestroy
public void Remind (String title, String message)
{
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent .PutExtra ("message", message);
notificationIntent .PutExtra ("title", title);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(context, 0 , notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
if (android.os.Build.VERSION.SDK_INT>16)
{
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+ 6*60*60*1000, broadcast);
}else
{
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 6*60*60*1000, broadcast);
}
}
Create a new JAVA file
public class Broadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent1) {
String message = intent1.getStringExtra ("message");
String title = intent1.getStringExtra ("title");
// This intent is fired when notification is clicked
Intent notificationIntent = new Intent(context, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.mipmap.ic_launcher);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Notifications Title");
// Content text, which appears in smaller text below the title
builder.setContentText("Your notification content here.");
// The subtext, which appears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText("Tap to view documentation about notifications.");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(0, builder.build());
}
Register this Receiver in Manifest
<receiver android:name=".Broadcast">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
You can do it by using alarm manager service and notification manager.

android notification only sound plays notification is not shown in notification drawer

i am trying to fire notification in at a particular time using AlarmManager and Notification manager. i am facing a strange problem. when notification is fired only sound plays but notification is not shown in the notification drawer.
i got an error in the log
04-26 11:32:09.217 1222-1222/? E/NotificationService﹕ WARNING: In a future release this will crash the app: com.example.shiv.selftweak
my code is .
The class which calls the AlarmManager
Intent intent1 = new Intent(this, FireNotification.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 1000, intent1, 0);
AlarmManager am = (AlarmManager)this.getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), pendingIntent);
FireNotification class
public class FireNotification extends Service {
#Override
public void onCreate() {
Intent intent = new Intent(this, MainActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(this, 1234, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Self tweak")
.setContentText("Habbits are waiting for last dones")
.setVibrate(pattern)
.setAutoCancel(false);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(false);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1234, mBuilder.build());
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Android Menifest
<service android:name=".FireNotification"></service>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
when notification fires only sound plays. but it is not getting shown in the notification drawer which shows no notification.
The problem is that you haven't specified mBuilder.setSmallIcon(R.drawable.ic_launcher).
Basically you have to set smallIcon, contentTitle and contentText. If you miss any of those the Notification will not be displayed at all! That's clearly specified HERE (also you can read more about notifications there as well).

Music player control in notification

how to set notification with play/pause, next and previous button in android.!
I am new with Android & also at stack overflow. So please bear with me.
I set notification when song is start to play like below :
`
#SuppressLint("NewApi")
public void setNotification(String songName){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.god_img, null, System.currentTimeMillis());
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_mediacontroller);
//the intent that is started when the notification is clicked (works)
Intent notificationIntent = new Intent(this, AudioBookListActivity.class);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentView = notificationView;
notification.contentIntent = pendingNotificationIntent;
notification.flags |= Notification.FLAG_NO_CLEAR;
//this is the intent that is supposed to be called when the button is clicked
Intent switchIntent = new Intent(this, AudioPlayerBroadcastReceiver.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
notificationManager.notify(1, notification);
}
`
I have create BroadcastReceiver like below :
`
private class AudioPlayerBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("intent action = " + action);
long id = intent.getLongExtra("id", -1);
if(Constant.PLAY_ALBUM.equals(action)) {
//playAlbum(id);
} else if(Constant.QUEUE_ALBUM.equals(action)) {
//queueAlbum(id);
} else if(Constant.PLAY_TRACK.equals(action)) {
//playTrack(id);
} else if(Constant.QUEUE_TRACK.equals(action)) {
//queueTrack(id);
} else if(Constant.PLAY_PAUSE_TRACK.equals(action)) {
// playPauseTrack();
System.out.println("press play");
} else if(Constant.HIDE_PLAYER.equals(action)) {
// hideNotification();
System.out.println("press next");
}
else {
}
}
}`
Now, I set custom notification successfully but how can i handle notification buttons and its events like play/pause, previous and next... etc. I also try using broadcast receiver but could not get any response.
Seeking solution and guidance from experts, please help me out.
Thanks in advance.
You need to set a custom intent action, not the AudioPlayerBroadcastReceiver component class.
Create a Intent with custom action name like this
Intent switchIntent = new Intent("com.example.app.ACTION_PLAY");
Then, register the PendingIntent Broadcast receiver
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 100, switchIntent, 0);
Then, set a onClick for the play control , do similar custom action for other controls if required.
notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
Next,Register the custom action in AudioPlayerBroadcastReceiver like this
<receiver android:name="com.example.app.AudioPlayerBroadcastReceiver" >
<intent-filter>
<action android:name="com.example.app.ACTION_PLAY" />
</intent-filter>
</receiver>
Finally, when play is clicked on Notification RemoteViews layout, you will receive the play action by the BroadcastReceiver
public class AudioPlayerBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){
// do your stuff to play action;
}
}
}
EDIT: how to set the intent filter for Broadcast receiver registered in code
You can also set the Custom Action through Intent filter from code for the registered Broadcast receiver like this
// instance of custom broadcast receiver
CustomReceiver broadcastReceiver = new CustomReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("com.example.app.ACTION_PLAY");
// register the receiver
registerReceiver(broadcastReceiver, intentFilter);

android get preferences from broadcast receiver

Well, i am an Android newbie. I am trying to write an application which has one activity which starts another activity (Preference Activity), and one BoradcastReceiver. They are all in three different files. My question is: How to share Preferences betweens these components, e.g. how to read preferences that are set in Preference Activity from Broadcast Receiver?
I have asked this same exact question before and here is the code I used:
public class BootupReceiver extends BroadcastReceiver {
private static final boolean BOOTUP_TRUE = true;
private static final String BOOTUP_KEY = "bootup";
#Override
public void onReceive(Context context, Intent intent) {
if(getBootup(context)) {
NotificationManager NotifyM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification Notify = new Notification(R.drawable.n,
"NSettings Enabled", System.currentTimeMillis());
Notify.flags |= Notification.FLAG_NO_CLEAR;
Notify.flags |= Notification.FLAG_ONGOING_EVENT;
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
Notify.contentView = contentView;
Intent notificationIntent = new Intent(context, Toggles.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notify.contentIntent = contentIntent;
int HELO_ID = 00000;
NotifyM.notify(HELLO_ID, Notify);
}
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.leozar100.myapp.NotifyService");
context.startService(serviceIntent);
}
public static boolean getBootup(Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(BOOTUP_KEY, BOOTUP_TRUE);
}
}
The service that I start does nothing I just initiate one because I think it just helps the broadcast receiver work. Also this broadcast receiver is registered in my manifest like so:
<receiver android:name=".BootupReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
Which starts on bootup requiring the permission android.permission.RECEIVE_BOOT_COMPLETED
Reference to my question can be found here
P.S. Welcome to stackoverflow

Categories

Resources