Notification tap event without showing an activity? - java

I want to assign an event that will fire when a notification is being tapped on, without showing an activity (like explained here).
How can I do that?

You can do this by registering a Broadcast Receiver. This way, you can run code in the receiver when your notification is clicked, without showing any UI whatsoever if you want.
Basic receiver code:
public class Provider extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
//Your code here
}
}
In the manifest:
<receiver android:name="Provider" />
Sample code for the notification:
public static void showNotification(Context context) {
CharSequence title = "title";
CharSequence message = "text";
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(<image>, title, System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
Intent notificationIntent = new Intent(context, Provider.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, pendingIntent);
notificationManager.notify(<notification id>, notification);
}

Related

Instead of pendingIntent, execute function in Notification.addAction() . Is it possible?

I want a method to be executed when I press a button on my notification. For that purpose I am adding an action with a PendingIntent to my notification:
Intent intent = new Intent(context, AlertActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Notification")
.setContentText("Click Here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.addAction(R.mipmap.ic_launcher, "Test2", pendingIntent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, notification);
That works, however I don't want to start an Activity when the user invokes the action. I just need to do some work.
For that purpose I implemented a Service which should be targeted by the PendingIntent instead:
public class MyServices extends IntentService {
public MyServices() {
super("MyServices");
}
#Override
protected void onHandleIntent(Intent intent) {
clearNotification();
}
public void clearNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(0);
Intent intent = new Intent(MyServices.this, MainActivity.class);
//Starting new activity just to check
startActivity(intent);
}
}
I create the PendingIntent like this:
final Intent intent = new Intent(context, MyServices.class);
final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
However when I invoke the action on my notification nothing happens. What am I doing wrong?
A Notification is not part of your application. It is managed by the OS. It just so happens that there are APIs you can use to show/cancel/etc notifications.
A pending intent allows for external code (Notifications for example) to launch your app/activity/service/broadcastreceiver. This cannot be done without a pending intent.
What my task is to execute some piece of code when a specific action button is clicked, and clear notification; without starting any activity
You don't have to start an activity. You can do it in a broadcastreceiver that has no UI. Or, as CommonsWare suggested, use an IntentService, depending on what what you are doing in your "piece of code". IntentServices handle work in a separate thread.

Broadcast receiver never receives intent

I have a problem with receiving notification. I am sure it is sent as I see log for sending. But I never receive it as I never see log or notification. I am not quiet sure what I am doing wrong.
And I don't want repeating alarm.
Using Nexus 7 on Marshmallow.
PracticeWordsActivity.java
public void setAlarm(int day){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(PracticeWordsActivity.this,AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
//alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis()+15000, pendingIntent);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+15000, pendingIntent);
Log.e(TAG,"Lift off");
}
AlarmService
public class AlarmService extends IntentService
{
private static final int NOTIFICATION_ID = 1;
private static final String TAG = "AlarmService";
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
public AlarmService() {
super("AlarmService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.e(TAG,"Alarm Service has started.");
Context context = this.getApplicationContext();
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("test", "test");
mIntent.putExtras(bundle);
pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Resources res = this.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker("TITLE")
.setAutoCancel(true)
.setContentTitle("TITLE2")
.setContentText("SUBJECT");
notificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Log.e(TAG,"Notifications sent.");
}
AlarmReceiver.java
public class AlarmReceiver extends WakefulBroadcastReceiver {
private static final String TAG = "AlarmReceiver";
Intent intent;
PendingIntent pendingIntent;
NotificationManager notificationManager;
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "BroadcastReceiver has received alarm intent.");
Intent service1 = new Intent(context, AlarmService.class);
context.startService(service1);
}
}
AndroidManifest.xml
I have set receiver and service after declaring last activity in AndroidManifest.
...
</activity>
<receiver android:name=".AlarmReceiver"
android:enabled="true"/>
<service android:name=".AlarmService" />
</application>
You're using AlarmManager.ELAPSED_REALTIME_WAKEUP to set the alarm. ELAPSED_REALTIME_WAKEUP means time elapsed since the device booted up.
If you want the alarm to be triggered 15 seconds after you set it, use:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+15000, pendingIntent);
or
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+15000, pendingIntent);
Also, I see you're triggering the alarm in WAKEUP mode and in your broadcast receiver you're starting a service. There is a chance that the device will go back to sleep before the service gets started. You can use WakefulBroadcastReceiver to prevent that.
You don't need to worry about repeating alarms, if you use the same intent to set a new alarm, the previous alarm that is using the same intent will be canceled.

When user taps on the push notification message, my app launches. How to make the app display the push message in full?

Good day!
I have successfully sent push notification message to my app on android, and when I tap on the message, it launches my app. May I ask how do I pass intent/bundle to MainActivity from the push notification so that when the app is launched, it can display the push notification message in full within the app? Thank you very much!
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmMessageHandler.class.getName());
showNotification(context, intent);
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
private void showNotification(Context context, Intent intent) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
String title = intent.getExtras().getString("nTitle");
String message = intent.getExtras().getString("nMessage");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context);
Notification notification = mBuilder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.face)
.setColor(context.getResources().getColor(R.color.wallet_holo_blue_light))
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.fuckya))
.setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message).build();
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
Regards,
Lorkh
Replace to:
Intent mainActivityIntent = new Intent(context, MainActivity.class);
String title = intent.getExtras().getString("nTitle");
String message = intent.getExtras().getString("nMessage");
mainActivityIntent.putExtra("nTitle", title);
mainActivityIntent.putExtra("nMessage",message);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainActivityIntent), 0);
And retrieve this values inside your MainActivity via getIntent();

android: notification doesn't do anything

hey all i'm making an application where the user's can send gcm messages to each other
the application is working very good and when i send a gcm message the receiver get it as a notification
and when the receiver click it it opens the homepage.class but the problem is that
when he click on the notification the Broadcast receiver does not receive it and doesn't make change's to the EditText, On the other hand if the receiver was using homepage.class when the message was received it make change's to the EditText (Working)
what could be the problem ???
some methods from my GCMIntentService
#Override
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, HomePage.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
#Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("message");
// notifies user
aController.displayMessageOnScreen(context, message);
generateNotification(context, message);
}
void displayMessageOnScreen(Context context, String message) {
Intent intent = new Intent("com.ms.gp.wefamily.DISPLAY_MESSAGE");
intent.putExtra("message", message);
// Send Broadcast to Broadcast receiver with message
context.sendBroadcast(intent);
}
and this is the code of my BroadcastReceiver
#Override
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString("message");
// Display message on the screen
Familyname.setText(newMessage);
}
};
please if anyone knows the answer tell me (Sorry for bad English)
Make sure you register the receiver on its parent activity. Once it's properly registered have it handle the received bundle. Pay attention to the sent value tags.

Cancel notification not working

I want to cancel/delete the notification after I click the addAction.
However it's not working. The notification is still there after the click.
I'm pretty sure this worked in an other project.
Can anyone see a stupid error I made, why its not working?
Actual code:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context){
String onderwerp = ("Medicatietijd");
String name = ("Het is tijd om je medicitie in te nemen.");
// Geluid notificatie
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Test.class), 0);
// De notificatie
Notification mNotification = new Notification.Builder(context)
.setContentTitle(onderwerp)
.setContentText(name)
.setSmallIcon(R.drawable.ninja)
.setSound(soundUri)
.addAction(R.drawable.ja, "Ja, ik heb ze ingenomen.", contentIntent)
.setAutoCancel(true)
.build();
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification.vibrate = new long[]{100, 200, 100, 500};
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
Solution:
In test activity OnCreate added this:
NotificationManager notificationManager
= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
If you decided to use Test activity to receive the intent of your addAction call, then you must cancel notification when you receive the intent in the activity.
I also recommend that you add requestCode for the intent.
Here is the code :
to set the requestCode modify this :
static final int REQ_CODE = 101; // some number
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, REQ_CODE,
new Intent(context, Test.class), 0);
to Handle intent in activity and dismiss the notification, in Test activity class :
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_CODE) {
// dismiss notification
notificationManager.cancel(0);
// handle your action
// ...
}
}
Hope that helps

Categories