How can I create notification which will close the app after clicking? - java

How can I create simple notification, which will close the application (in multitasking) after click? Thanks. (Java, Android)

first we should create notification that call an activity :
Intent intent = new Intent(this, YourClass.class);
intent.putExtra("NotiClick",true);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
Notification Noti;
Noti = new Notification.Builder(this)
.setContentTitle("YourTitle")
.setContentText("YourDescription")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, Noti);
}
Then in the onCreate() of your class do this:
Bundle extras = getIntent().getExtras();
if(extras == null)
{
//not being clicked on
}
else if (extras.getBoolean("NotiClick"))
{
//being clicked
}
and for completely close application you can kill process :
android.os.Process.killProcess(android.os.Process.myPid());

Related

Extras are null inside onNewIntent() method

I have a timer and when it ends if the user has it's app in background it sends a local notification, the local notification takes the user to the Timer Activity, this should fire the onNewIntent() method (that works on a device running Android L) where I check for the Extras I passed, the problem is that the Extras are null.
In the manifest I've declared my activity as: android:launchMode="singleTop"
And I create the notification like this:
Intent notificationIntent = new Intent(getBaseContext(), CookingTimer.class);
notificationIntent.putExtra("stopTimer", true);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification noti = new Notification.Builder(this)
.setContentTitle("Il Countdown รจ terminato!")
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContentIntent(pIntent).build();
//.addAction(R.drawable.ic_launcher, "Stop", stopTimer)
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
Why it doesn't work?
EDIT:
Just found that the Extra I pass using notificationIntent.putExtra("stopTimer", true); is null when I check inside the onNewIntent() method

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();

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

Android - Vibrate without displaying new Activity?

I have the following code in an android app. What it currently does is, at the specified time passed with the Calendar when variable, it opens up the RunningActivity (which is blank), vibrates, and sends a notification. Even if I've pressed the home button and it's running in the background, it starts a new blank RunningActivity and vibrates and sends a notification. I'm trying to figure out how to do all the stuff in the RunningActivity (Vibrate and send a notification) without opening up the blank RunningActivity, allowing the application to stay in the background.
I do NOT need help with actually calling the notification or vibration. I just need to know how to run the actions in the RunningActivity onCreate at a specific time witout opening/showing the RunningActivity. As seen below, I setup a PendingIntent with an AlarmManagager, the issue is that it is launching an Activity and showing it when all I want it to do is vibrate/send a notification.
public void startAlarm(Activity activity, Calendar when){
currentTimerHour = when.get(Calendar.HOUR);
currentTimerMin = when.get(Calendar.MINUTE);
Intent intent = new Intent(activity, RunningActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)activity.getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pendingIntent);
}
RunningActivity Class:
public class RunningActivity extends Activity {
#Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
}
To send Notification From Background:
public void createNotification(Context context) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(context,Myexample.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification noti = new Notification.Builder(context)
.setContentTitle("My Title")
.setContentText("My message.")
.setSmallIcon(R.drawable.app_icon)
.setContentIntent(pIntent).build();
#SuppressWarnings("static-access")
NotificationManager notificationManager =
(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
noti.flags |= Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, noti);
}
You can use service. Add your vibrator class on Service and call it when you need need it. You can also create a method on your class and call it when you need it.
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);

make notification clickable and undestroyable

I tried to create a notification that starts a activity by clicking on it and which you can't swipe away.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("DroidSchool")
.setContentText("DroidSchool l\u00E4uft im Hintergrund...");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_FROM_BACKGROUND);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mId = 1234567890;
mNotificationManager.notify(mId, mBuilder.build());
with the code above the notification gets displayed, but nothing happens when I click on it and you can swipe it away.
To keep the Notification, in that way the user can't click it away in any way, add this flag
Notification mNotification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(mId, notification);
To start an Activity you have to use this flag for your Intent
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Do like this:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("DroidSchool")
.setContentText("DroidSchool l\u00E4uft im Hintergrund...");
Intent intent = new Intent(YourActivity.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification noti = mBuilder.build();
noti.flags |= mBuilder.build().FLAG_NO_CLEAR | mBuilder.build().FLAG_ONGOING_EVENT;
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, noti);
You want a foreground service as detailed here
It's worth noting that only android 4.3 added the persistent notification you seem to be after and it can be overriden by the users settings.
try using like this
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_UPDATE_CURRENT);
in MainActivity.java
Dont not consume your notification; ie instead of calling below 2 line code in oncreate() call under onDestro()
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(mId);
You can use NotificationCompat.Builder's .setOngoing(true), use it like this:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setContentTitle("Downloading Something")
.setContentText("Downloading")
.setSound(null)
.setDefaults(0)
.setOngoing(true);
// Makes it so the notification is clickable but not destroyable by swiping-away or hitting "clear all"

Categories