Displaying push notification while app is not open - android

I'm trying to create notifications for my app that sends notifications when a certain task is due. Each task has a deadline time so I want to send a notification for each task when their deadline has passed.
My main class is called RecyclerViewDemoActivity and inside the onCreate() I have this:
public void setNotification()
{
Intent intent=new Intent(this,NotificationClass.class);
AlarmManager manager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
PendingIntent pendingIntent= PendingIntent.getService(this, 0, intent, 0);
// hardcoding the time just for this example
manager.set(AlarmManager.RTC_WAKEUP,1449208683000,pendingIntent);
}
and I have a NotificationClass that looks like this:
public class NotificationClass extends Service {
#Override
public void onCreate()
{
Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification nBuilder= new Notification.Builder(this)
.setContentTitle("This task is due!")
.setContentIntent(pIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,nBuilder);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grokkingandroid.samplesapp.samples.recyclerviewdemo" >
<uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<application
android:name="com.teamvallartas.autodue.RecyclerViewDemoApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.teamv.RecyclerViewDemoActivity"
android:label="#string/app_name"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I looked at this resource for the code above and also Vogella's resource on notifications but I don't know why this is not working.

Check if onCreate of Service class is getting called. If it is, then the problem is "You placed your code at wrong method.".
You need to move code into onStartCommand(Intent intent, int flags, int startId).
Like
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification nBuilder= new Notification.Builder(this)
.setContentTitle("This task is due!")
.setContentIntent(pIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,nBuilder);
// If we get killed, after returning from here, restart
return START_STICKY;
}
Update your manifest and add this entry to it
<service android:name=".NotificationClass" />

you can do it in this way ,
1st > create one local broadcast receiver ,
inside onReceive() method , put your code stuff for generate notification
,that is your setNotification() method .
2nd > you just register that broadcast receiver inside onCreate() and unregister it inside onPause() or onDestory() method . like this ...
ReceiverActivity.java
public void onCreate(Bundle savedInstanceState) {
...
// Register your broadcast receiver here ...
// with actions named "custom-event-name"...
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
protected void onDestroy() {
// Unregister your receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
//here comes our receiver ...
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//called setNotification() here ...
}
};
Now let suppose you want to generate notification on click event of your button then fire intent like this,
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "Its me!!!!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
your **setNotification()**should be like this ..
public void Notification(Context context, String message) {
// Set Notification Title
String strtitle = context.getString(R.string.notificationtitle);
// Open NotificationView Class on Notification Click
Intent intent = new Intent(context, NotificationView.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", message);
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create Notification using NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
// Set Icon
.setSmallIcon(R.drawable.logosmall)
// Set Ticker Message
.setTicker(message)
// Set Title
.setContentTitle(context.getString(R.string.notificationtitle))
// Set Text
.setContentText(message)
// Add an Action Button below Notification
.addAction(R.drawable.ic_launcher, "Action Button", pIntent)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}

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.

Run Android Notifications when App is closed without GCM/Firebase

I am working on an App where I want to show Push Notifications. Please note that since it is my client's requirement NOT to use any third party services, so using GCM/Firebase is out of question.
I am successfully able to show the notification from Service using the below code.
public class SendNotificationService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
CharSequence title = "Notification Title";
CharSequence message = "This is a test notification.";
Drawable drawable= ContextCompat.getDrawable(this,R.drawable.brand_icon_color);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.brand_icon_small_color)
.setLargeIcon(bitmap)
.setAutoCancel(true)
.setContentTitle(title)
.setOngoing(false);
mBuilder.setContentText(message);
mBuilder.setTicker(message);
mBuilder.setWhen(System.currentTimeMillis());
NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
mBuilder.setContentIntent(pendingIntent);
notificationManager.notify(0, mBuilder.build());
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
}
}
I am starting this service through my AsyncTask onPostExecute method.
Intent intentService = new Intent(context, SendNotificationService.class);
context.startService(intentService);
I created this following a number of tutorials and found that if I will go to my Running Apps in Android Settings, I will be able to see this service running. But I was unable to locate any such service.
Now the problem is when I close my Application, the notification also disappears. I want it to stay until the user takes any action.
In addition to this, I want this service to start with phone startup even if the app is not started.
1) Add the permission to the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) Add a receiver to the manifest to run on boot:
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
In MyBroadcastReceiver.java:
package com.example;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}

Can't swipe-delete a notification from service

I have a service which downloads data, runs in a separate process (so that it doesn't die/restart when the app is closed) and shows a notification with it's progress. I want to be able to stop the service if the user swipe-deletes the notification, but have so far been unable to do it. Relevant code below:
DatabaseDownloadService.java
public class DatabaseDownloadService extends Service
{
private final static int NOTIFICATION_ID = 1337;
private final static String NOTIFICATION_DISMISSAL_TAG = "my_notification_dismissal_tag";
private NotificationManager mNotificationManager;
#Override
public void onCreate()
{
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getNotification("Downloading database...");
startForeground(NOTIFICATION_ID, notification);
startDownloadingStuff();
}
private Notification getNotification(String text)
{
NotificationDismissedReceiver receiver = new NotificationDismissedReceiver();
registerReceiver(receiver, new IntentFilter(NOTIFICATION_DISMISSAL_TAG));
Intent intent = new Intent(this, NotificationDismissedReceiver.class);
PendingIntent deleteIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, intent, 0);
return new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentText(text)
.setDeleteIntent(deleteIntent)
.build();
}
public class NotificationDismissedReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
int notificationId = intent.getExtras().getInt(NOTIFICATION_DISMISSAL_TAG);
Toast.makeText(context, "Download cancelled", Toast.LENGTH_SHORT).show();
// Do more logic stuff here once this works...
}
}
}
AndroidManifest.xml
<application
... properties and activities go here...>
<service
android:name=".DatabaseDownloadService"
android:process=":dds_process"
android:enabled="true"/>
<receiver
android:name="com.myapp.DatabaseDownloadService$NotificationDismissedReceiver"
android:exported="false"/>
</application>
As far as I can tell, the .setDeleteIntent() should make the notification swipe-deletable, which should then send a broadcast, which should then be caught by my NotificationDismissedReceiver. However, as it stands, I can't even swipe-delete the notification, and I never see the "Download cancelled" Toast...
You can call to stop the service from foreground, passing false, means not remove the notification. For Android N and above, you can pass STOP_FOREGROUND_DETACH also.
stopForeground(false);
After that you can stop the service by yourself also.
stopSelf();
Instead of using startForeground(), use :
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify("tag", NOTIFICATION_ID, notification);

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.

Is it possible to send a LocalBroadcast from a notification action?

I would like to send a LocalBroadcast when clicking on a button inside a notification. I know how to do that with a regular broadcast, but I would like to keep the broadcast inside my app. Is this possible?
The code I have is roughly:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setContentTitle("Title")
.setContentText("content")
.setSmallIcon(R.drawable.icon1)
.setContentIntent(pIntent)
.setAutoCancel(true);
Intent myButtonIntent = new Intent(BUTTON_PRESSED);
// the following line gives me a normal broadcast, not a LocalBroadcast
PendingIntent myButtonpIntent = PendingIntent.getBroadcast(context, 12345, myButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.icon2, "OK", myButtonpIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
And also:
BroadcastReceiver bReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BUTTON_PRESSED)) {
// do something
}
}
};
LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BUTTON_PRESSED);
bManager.registerReceiver(bReceiver, intentFilter); // I want to use the LocalBroadcastManager
// registerReceiver(bReceiver, intentFilter); // Instead, I have to use this line for a non-local broadcast
No.
First of all, LocalBroadcastManager is part of the support package (an optional library you add to your application), not part of the system itself.
Secondly, even if it were, the notification service is used by all applications. Since it's a shared resource, there is nothing "local" that occurs when you post a notification.
this might work(it works for me)
add your BroadcastReceiver to manifest.xml
<!-- If this receiver listens for broadcasts sent from the system or from
other apps, even other apps that you own, set android:exported to "true". -->
<receiver android:name=".myBroadcastReceiver" android:exported="false">
<intent-filter>
<action android:name="some" />
</intent-filter>
</receiver>
creating a Notification and add action( .addaction() )
and sending Broadcast to BroadcastReceiver
(you can use the helper function)
Intent Rintent = new Intent(this , YOUR_BroadcastReceiver_CLASS.class );
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
createNotificationChannel(ChanelID ,"name " , "Desc" );
startForeground(FLAG_FORGRANDONLLINE, new NotificationCompat.Builder(ServiceFindTask.this,
NotifID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.mipmap.somet)
.setContentTitle(getString(R.string.app_name))
.setContentText("Service is running ")
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setVibrate(new long[]{1000,100})
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
// Sending a action for BroadcastReceiver class
.addAction(R.drawable.body,"GO offline" , makePendingIntent(SERVICE_TO_CLIENT_GO_OFFLINE , null , Rintent))
.build());
// Helper function
public PendingIntent makePendingIntent(Integer action , #Nullable String data ,Intent intent) {
intent.setAction( action.toString());
if(data != null){
intent.putExtra("kay", data);}
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
return pendingIntent;
}
receive the action and create LocalBroadcast using LocalBroadcastManager
based on your notification action
public class myBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (Integer.parseInt(action)){
case Service.SERVICE_TO_CLIENT_GO_OFFLINE:
helpLocalBroadcastManager(intent , context , Service.SERVICE_TO_CLIENT_GO_OFFLINE , null);
break;
}
}
private void helpLocalBroadcastManager(Intent intent ,Context context ,Integer action , #Nullable String data ) {
intent = new Intent(action.toString());
// Adding some data
if(data != null){
intent.putExtra("kay", data);}
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
now you can receive the LocalBroadcast in any activity that is connect to BroadcastReceiver like this:
private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (Integer.parseInt(action)){
case Service.SERVICE_TO_CLIENT_GO_OFFLINE:
Toast.makeText(Activity_Main.this , "This is massage from Activity_Main " , Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this)
.registerReceiver(messageReceiver, new IntentFilter(String.valueOf(ServiceFindTask.SERVICE_TO_CLIENT_GO_OFFLINE)));
}
this question was for 8 years ago but this was something i needed now and this is how i did it THANKS FOR READING

Categories

Resources