I want to make a notification from BroadcastReceiver. I'm using this code in my activity and it works fine but I can't make a notification from BroadcastReceiver . Could you help me to solve this problem :
Random rd;rd= new Random ();
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(link));
PendingIntent pending=null;
pending = PendingIntent.getActivity(ctx, 0, notificationIntent, pending.FLAG_UPDATE_CURRENT);
Notification myNotification = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(false).setLargeIcon(remote_picture)
.setContentTitle(onvan).setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg).setContentIntent(pending).build();
notificationManager.notify(rd.nextInt(75), myNotification);
The problem is , this code does not make a notification and no notification is showing in the tray .as I say , I run this code in Activity and it works find but in BroadcastReceiver it does not make any notifications
To execute the code inside BroadcastReceiver you have to call sendBroadcast() method or set some action in your Manifest file like
<receiver android:name="Your package name.ReceiverName">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
//set your action here
</intent-filter>
</receiver>
Related
I am a newbie in android development.
I create a background service for receive pushNotification (with our own socket service, not FCM).
And now my device receive message and show notification successfully. But when I click the notification, it not return to my app.
When I click notification, show the error below:
ActivityManager: Unable to start service Intent { cmp=com.my.app/package.name.AppActivity } U=0: not found
Here is my code:
public static void setNotification(Service service, String message) {
NotificationManager manager = (NotificationManager) service.getSystemService(NOTIFICATION_SERVICE);
String appName = service.getString(R.string.app_name);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(service)
.setContentTitle(appName)
.setContentText(message)
.setContentIntent(getDefaultIntent(service))
.setWhen(System.currentTimeMillis())
.setOngoing(false)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(BitmapFactory.decodeResource(service.getResources(), R.drawable.icon))
.setSound(alarmSound);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(1, notification);
}
private static PendingIntent getDefaultIntent(Service service) {
Intent intent = new Intent(service, AppActivity.class);
PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return pendingIntent;
}
}
MainActivity setting in AndroidManifest.xml
<activity android:name="package.name.AppActivity" android:configChanges="orientation|screenSize" android:label="#string/app_name" android:launchMode="singleTask" android:screenOrientation="landscape" android:theme= "#android:style/Theme.NoTitleBar.Fullscreen" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Please guide me what I am missing or doing wrong in this code. Many thanks.
I pass same id in padding intent and manager.notify(0, notification);
And use PendingIntent.getActivity instead of PendingIntent.getService
it works!
I got the problem you only cancel the current notification thats why Intent is not firing the activity Change your Pending intent
from
PendingIntent.FLAG_CANCEL_CURRENT);
to
PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
Good Morning,
I've made an application that implements GpS Location. I have a service that save my location on LocationChanged event. To avoid that Android close my app I start a notification and all works well. But now, I want that when I click on notification from Action Bar the app come back in foreground.I use fragment and the map fragment is called MappaFragment. I read a lot of messages but It seems not resolve my issue. Below my code, any suggestion is appreciated !
Alex
This is my monitoring Service:
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.STARTFOREGROUND_ACTION)) {
Log.i(TAG, "Received Start Foreground Intent ");
Intent notificationIntent = new Intent(getApplicationContext(), LocationMonitoringService.class);
Bundle extras = intent.getExtras();
numeroTraccia = extras.getInt("numeroTraccia");
itinerario = extras.getString("itinerarioRiferimento");
notificationIntent.setAction(Constants.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Intent.FLAG_ACTIVITY_CLEAR_TASK);
setGiornoRiferimento(gg.checkDayLong(this));
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, new Intent(getBaseContext(),MappaFragment.class), 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), com.example.alex.myApp.R.drawable.smallicon );
Notification.BigTextStyle bigText = new Notification.BigTextStyle();
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("MyApp")
.setTicker(getString(R.string.track))
.setStyle(bigText.bigText(getString(R.string.track)))
.setSmallIcon(R.drawable.smallicon)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
This is my Manifest:
<activity android:name="com.example.alex.myApp.MainActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize|keyboardHidden" />
<activity
android:name="com.example.alex.myApp.SplashScreen"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.alex.myApp.services.MonitoringService"
android:enabled="true"/>
<receiver
android:name="com.example.alex.myApp.RestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartWhenStopped">
<intent-filter>
<action android:name="com.example.alex.myApp.ActivityRecognition.RestartSensor"/>
</intent-filter>
</receiver>
Thanks in advance !
Alex
First of all,
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getBaseContext(),MappaFragment.class), 0);
this is incorrect. Fragment can't be opened using intent. You need to launch an activity, then redirect to required fragment.
Next thing is, if app is in background and you click on the notification, it will open launcher activity. So in launcher activity you need to check for bundle object and there you can redirect to particular activity or fragment.
Check this post: Push notification works incorrectly when app is on background or not running and Open specific Activity when notification clicked in FCM it will help you to better understand how FCM works when app is in background and foreground.
Create a BroadCast Receiver like below:
public static class ActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("open_activity")) {
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClass(AppContext.getContext(), MappaFragment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);
}
}
}
And then, Use this notificationIntent.setAction("open_activity");
And Change your PendingIntent to:
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, new Intent(AppContext.getContext(), ActionReceiver.class), 0);
NOTE: For USing This you need to Remove These Lines:
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification)
What I'm suggesting is to use a BroadcastReceiver to receive whatever you want to do in Your Notification.
Also, If this isn't working try Adding .setAction(Intent.ACTION_MAIN) to Your Notification like Below:
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("MyApp")
.setTicker(getString(R.string.track))
.setStyle(bigText.bigText(getString(R.string.track)))
.setSmallIcon(R.drawable.smallicon)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.setAction("open_activity")
.build();
I am developing a small app in which I want a background service to send a notification and when the user clicks the notification it must launch the appropriate activity. I am posting the code here for the notification and my problem is that the notification gets displayed on the status bar but when i click it it does not launch the required activity(instead it is launching the mainactivity). Can somebody suggest where I am going wrong. Please help.
Intent intent = new Intent(this, IncidentDetail.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getService(this,0 /* Request code */
, intent,PendingIntent.FLAG_UPDATE_CURRENT);
//here i tried with both getService and getActivity
/*PendingIntent pendingIntent = PendingIntent.getActivity(this,0
, intent,PendingIntent.FLAG_UPDATE_CURRENT);*/
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
;
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Below is my manifest file
<service android:name=".MyFirebaseMessagingService" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".IncidentDetail"
android:label="#string/title_activity_incident_detail"
android:exported="true"
android:launchMode="singleTop">
</activity>
Problem in this line.
PendingIntent pendingIntent = PendingIntent.getService(this,0 /* Request code */
, intent,PendingIntent.FLAG_UPDATE_CURRENT);
It shoule be.
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* Request code */
, intent,PendingIntent.FLAG_UPDATE_CURRENT);
Cause Intent is calling an activity not a service .
I'm trying to dismiss a notification from an .addAction() without having to open the app. The problem is when the button is pressed nothing happens, the onReceive() method doesn't trigger.
Here is the code on the MainActivity:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("id", SOMENUMBER);
PendingIntent pIntent = PendingIntent.getBroadcast(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
notification.setContentTitle("");
notification.setContentText(t);
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setOngoing(true);
notification.addAction(R.mipmap.ic_launcher, "Dismiss", pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(SOMENUMBER, notification.build());
And on other class I have the reciever:
public class Notification extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(intent.getIntExtra("id", 0));
}
}
And the reciever on the AndroidManifest.xml file:
<receiver android:name=".MainActivity">
<intent-filter>
<action android:name="io.github.seik.Notification" />
</intent-filter>
</receiver>
Your naming conventions are confusing. Android already has a class called Notification, so you probably shouldn't call your receiver Notification :-(
If MainActivity extends Activity then you need to have a manifest entry for it that looks like this:
<activity android:name=".MainActivity"/>
For your BroadcastReceiver, you need a manifest entry like this:
<receiver android:name=".Notification"
android:exported="true"/>
Since you are using an explicit Intent to launch your BroadcastReceiver, you don't need to provide an <intent-filter> for it. Since the BroadcastReceiver will be started by the NotificationManager, you need to make sure that it is exported.
You then need to create the PendingIntent so that it actually launches your BroadcastReceiver, so change this:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
to this:
Intent notificationIntent = new Intent(mContext, Notification.class);
My problem is I want to cancel an ongoing notification only if cancel
option is selected in the app, but whenever I clear memory on "Task
Manager/RAM" tab of my android device my notification disappears.
What can I do to make my ongoing notification stay even if I clear memory?
I created an ongoing notification in a class that extends BroadcastReciever class.In my OnGoingNotificationReciever(extends BroadcastReciever):
Intent mainAct = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 555, mainAct, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(resID).setContentTitle(city).setContentText(temperature);
mBuilder.setContentIntent(contentIntent);
mBuilder.setOngoing(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
Then I set an AlarmManager to start this BroadcastReciever and repeat every 5 minutes:
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent i7 = new Intent(getApplicationContext(), OnGoingNotificationReciever.class);
PendingIntent ServiceManagementIntent = PendingIntent.getBroadcast(getApplicationContext(), 1111111, i7, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), 5 * 60 * 1000, ServiceManagementIntent);
This works perfectly and does what I want to do(e.g when I close the app, notification stays on the status bar) except it disappears when clearing memory.
Note: In Yahoo Weather application it does what I want to do, but I couldn't find how on the Internet.
After a lot of search I finally found a solution to this problem.
In my Manifest.xml I wrote the following:
<receiver android:name=".OnGoingNotificationReciever" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<data android:scheme="package" android:path="com.example.havadurumumenu" />
</intent-filter>
</receiver>
PACKAGE_RESTARTED is called when you clear memory, and setting this restarts your receiver after clearing memory.