Notification OnClick Event - android

I want to call the Activity NotificationReceiver, when I click onto an android notification.
The notification is already shown correctly, but when I click onto the notification nothing happens.
Here is the code for the notification:
private void notification_anzeigen2(){
Log.d("Test2", "Test2 ");
Intent intent = new Intent(this, NotificationReceiver.class);
intent.putExtra("NotiClick",true);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, Intent.FILL_IN_ACTION);
Notification n = new Notification.Builder(this).setContentTitle("GestureAnyWhere Hintergrundservice")
.setContentText("Bitte klicken, um den Hintergrundservice zu beenden")
.setContentIntent(pIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, n);
Log.d("Test3", "Test3 ");
}
And here is the activity:
public class NotificationReceiver extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null)
{
Log.d("Test4", "Test4");
}
else if (extras.getBoolean("NotiClick"))
{
Log.d("Test5", "Test5");
stopService(new Intent(getApplicationContext(), HintergrundService.class));
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
}
Thanks a lot.

Try:
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
You pass as a flag a constant that has nothing to do here, so its value can match to an undesired flag, see PendingIntent doc.
It says: "May be FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, or any of the flags as supported by Intent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens."

Related

Android Notification tap cause crashes the app due to Activity intent

I have MainActivity and UserAcitivity, I have passed some values to UserActivity through intent.
from the UserActivity, I call Notification then notification appeared, I made notification tap to
start the UserActivity by Pending Intent. When the Notification tap the App crashes because the values passed from MainAcitvity become null.
I can't Use SharedPreferences because the Value conflict for another UserAcitivity(the passed value was unique for every user)
example code is here:-
This is MainAcitvity
public void buttonClick(View view){
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("myname","ashiqueHira");
startActivity(intent);
}
This is SecondAcivity Oncreate method;
String heading= "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
heading = intent.getStringExtra("myname");
Toast.makeText(this, heading, Toast.LENGTH_SHORT).show();
}
This is my Notification method
public void notificationPops(){
Intent intent = new Intent(this, SecondActivity.class);
createNotificationChannel();
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_vibration_black_24dp)
.setContentTitle("Token Reminder")
.setContentText("Dismiss the Alarm by Clicking this")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVibrate(new long[] { 100, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000 })
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"myChannel",
NotificationManager.IMPORTANCE_HIGH
);
serviceChannel.enableVibration(true);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
This is a similar condition that I have. The difference is I have many usages for the getIntent value
and that value is unique for every Activity.
Thanks in Advance
So, basically you get NullPointerException. For reducing this problem change youe SecondActivity code like this:
String heading= "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
if(intent.getStringExtra("myname")!= null){
heading = intent.getStringExtra("myname");
Toast.makeText(this, heading, Toast.LENGTH_SHORT).show();
}
}
This will reduce your nullException error and your app cannot crash.
Another thing If you always need heading value pass through intent. Then pass the value also from notification pendingIntent and get it from SecondActivity
I found a way to solve this problem by adding and replacing the following code
in the notificationPops() method
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("yourName",heading);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
this will get you the value to the activity when the activity stats by notification taps.
Please post if other best practices to solve the problem above

Checking pending intent availablity status not working

Am trying to getting pending intent. Its returning intent fine when i click notification. But it not returning any thing when i open my app through launcher icon its not returning the pending intent. I searched many links but am not get anything.
creating pending intent from service
Intent in = new Intent(this, MainActivity.class);
in.setAction(action);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
in.putExtras(bundle);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, in,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Wiphone")
.setContentText(callStatus)
.setSmallIcon(R.drawable.ic_wifi)
.setWhen(System.currentTimeMillis())
.setAutoCancel(false)
.setOngoing(true)
.setPriority(Notification.FLAG_FOREGROUND_SERVICE)
.setContentIntent(pendIntent);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(10, notification);
getting pending intent in activity when user launch app through launcher
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent alarmIntent = new Intent();
alarmIntent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, alarmIntent,
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
Log.d(TAG, "has pending intent");
}
else {
Log.d(TAG, "no pending intent");
}
}

Android - create notifications

I have question about notifications. I want to build an app with one buttons called (add notification) when I press add notification a notification is created Then, if I press the notification it takes me back to the activity.
I managed to create a notification but when i press on it, it makes nothing. What do I have to add so the notification sends me back to the activity?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
NotificationManager nmanger;
static int id=1;
public void buclick(View view) {
NotificationCompat.Builder nbuild= (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Danger")
.setContentText("the raining is comming soon")
.setSmallIcon(R.drawable.amule);
nmanger =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nmanger.notify(id,nbuild.build());
id++;
}
Create PendingIntent, then set it to builder:
Intent intent = new Intent(this, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder nbuild = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Danger")
.setContentText("the raining is comming soon")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.amule);
Try this code
Intent intent = new Intent(this, NameOfClassYouWantToOpen.class);
// Create pending intent and wrap our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
try {
// Perform the operation associated with our pendingIntent
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
http://codetheory.in/android-pending-intents/
What is an Android PendingIntent?

how to make pressing on the notificaton text close the app not open other activity

I am developing a flashLight app and I faced a problem in notification which is : When I press the notification text I want to turn of flash and close the whole app , How can I modified the notification method to do that ??
I tried to make anthor activity and put turn of and close app methods in it, but it does not work .
please help and thanks in advance .
this is my notification method
public void getNotification()
{
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pIntent)
.setContentTitle(res.getString(R.string.notification_title))
.setContentText(res.getString(R.string.notification_text))
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_msg));
// Build the notification:
Notification notification = builder.build();
// Get the notification manager:
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Publish the notification:
final int notificationId = 0;
notificationManager.notify(notificationId, notification);
}
If you use the same Activity, then the onCreate method will be called again. You can send one extra with your Intent that indicates it is an Intent generated from the click of notification. In your Activity onCreate, check for this extra and call finish() if it is present.
public void getNotification() {
Intent intent = new Intent(this, FlashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("origin", "notification");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pIntent)
.setContentTitle(res.getString(R.string.notification_title))
.setContentText(res.getString(R.string.notification_text))
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_msg));
// Build the notification:
Notification notification = builder.build();
// Get the notification manager:
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Publish the notification:
final int notificationId = 0;
notificationManager.notify(notificationId, notification);
}
And in your onCreate method in FlashActivity check the extra.
#Override
public void onCreate(Bundle savedInstanceState) {
...
if("notification".equals(getIntent().getStringExtra("origin"))) {
finish();
}
}
I believe you can use finish() on your Activity when the notification ils pressed.
EDIT: How to close any activity of my application by clicking on a notification?
You want to use PendingIntent.
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("FINISH",true);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
// Build the notification:
Notification notification = builder.build();
//rest of your methods to show notification
In your MainActivity update depending on your code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
#Override
public void onNewIntent(Intent intent){
setContentView(R.layout.activity_main);
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("FINISH"))
{
finish();
}
}
}

Passing Data from Android Notifications

I have built a notification and am displaying it properly, but I can't figure out how to pass data to the activity. I pulled one string from the intent to display as the title of the notification, but I need to pull a 2nd string, and have the NotificationHandlerActivity process it.
//inside intentservice
private void sendNotification(Bundle extras) {
Intent intent=new Intent(this, NotificationHandlerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", extras.getString("link"));
mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
long[] vibrate = {100L, 75L, 50L};
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha)
.setContentTitle(extras.getString("title"))
.setOngoing(false)
.setAutoCancel(true)
.setVibrate(vibrate);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
//Inside NotificationHandlerActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
}
You should use the extras on your Intent. Because your intent is currently anonymous, you cannot do so. Extras are basic key-value stores. See below:
public static final String KEY_SECOND_STRING = "keySecondString";
...
...
String secondString = "secondString";
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, NotificationHandlerActivity.class);
intent.putExtra(KEY_SECOND_STRING, secondString);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
...
then, from your NotificationHandlerActivity, you can access that secondString from the intent.
#Override
public void onCreate(Bundle sIS){
super.onCreate();
String secondString = getIntent().getStringExtra("keySecondString");
...
}
use it like this :
Intent intent=new Intent(this, NotificationHandlerActivity.class);
intent.putExtra("key", "value");
mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
long[] vibrate = {100L, 75L, 50L};
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha)
.setContentTitle(extras.getString("title"))
.setOngoing(false)
.setAutoCancel(true)
.setVibrate(vibrate);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Apparently using 0 as the requestCode when calling getActivity() on the PendingIntent isn't the way to go. I updated it to just use System.currentTimeMillis() and that seemed to work. I'm assuming that the first time I built the notification, using 0 as the requestCode, the extra wasn't present.

Categories

Resources