Android - create notifications - android

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?

Related

notification buttons (.addaction) not launching activity

I'm attempting to make a notification that has two buttons which do two different things by running two different activities. The notification and its buttons appear on the notification bar fine, however pressing on either of the buttons fails to launch the designated activity.
Here is the code:
private void addNotification() {
int requestID = (int) System.currentTimeMillis();
NotificationCompat.Builder builder = (android.support.v7.app.NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ibutton)
.setContentTitle("Timer running..")
.setContentText(timerString);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
//Add buttons to notification
//First make the intent
Intent pauseIntent = new Intent(this, pauseActivity.class);
//Wrap it in pending intent to trigger later
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
//Same again for stop button
Intent stopIntent = new Intent(this, stopActivity.class);
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, requestID, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.stop, "Stop", stopPendingIntent);
// Add as notification
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mNotificationId = 001;
notificationManager.notify(mNotificationId, builder.build());
}
EDIT: An example of one of the activities I am trying to launch:
public class stopActivity {
public stopActivity() {
MainActivity.stopped = true;
}
}
If there is any easier way of simply changing the value of a variable in MainActivity from the button in the notification bar then I am also keen to hear that but as far as I can tell the only option is to launch a new activity
EDIT: An example of one of the activities I am trying to launch:
public class stopActivity { public stopActivity() {
MainActivity.stopped = true; } }
This is not an Activity. An Activity extends Activity!
This is just a POJO class and you cannot start it by putting it in a PendingIntent the way you are doing.
You would be better off by just using an Intent for MainActivity with an "extra" to change a value in it. Here's an example:
Intent pauseIntent = new Intent(this, MainActivity.class);
pauseIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pauseIntent.putExtra("pause", true);
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
Then, in MainActivity.onNewIntent():
if (intent.hasExtra("pause")) {
this.paused = true; // whatever you want to do when "pause" is pressed
}

Pending Intent not receiving the putExtraBudle for different notificationId

I am using the code of PingService.java https://github.com/android/platform_development/blob/master/samples/training/notify-user/src/com/example/android/pingme/PingService.java
PingService.Java
/**
* PingService creates a notification that includes 2 buttons: one to snooze the
* notification, and one to dismiss it.
*/
public class PingService extends IntentService {
private NotificationManager mNotificationManager;
private String mMessage;
private int mMillis;
NotificationCompat.Builder builder;
public PingService() {
// The super call is required. The background thread that IntentService
// starts is labeled with the string argument you pass.
super("com.example.android.pingme");
}
#Override
protected void onHandleIntent(Intent intent) {
// The reminder message the user set.
mMessage = intent.getStringExtra(CommonConstants.EXTRA_MESSAGE);
// The timer duration the user set. The default is 10 seconds.
mMillis = intent.getIntExtra(CommonConstants.EXTRA_TIMER,
CommonConstants.DEFAULT_TIMER_DURATION);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
String action = intent.getAction();
// This section handles the 3 possible actions:
// ping, snooze, and dismiss.
if(action.equals(CommonConstants.ACTION_PING)) {
issueNotification(intent, mMessage);
} else if (action.equals(CommonConstants.ACTION_SNOOZE)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.snoozing));
// Sets a snooze-specific "done snoozing" message.
issueNotification(intent, getString(R.string.done_snoozing));
} else if (action.equals(CommonConstants.ACTION_DISMISS)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
}
private void issueNotification(Intent intent, String msg) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Sets up the Snooze and Dismiss action buttons that will appear in the
// expanded view of the notification.
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Constructs the Builder object.
builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
/*
* Sets the big view "big text" style and supplies the
* text (the user's reminder message) that will be displayed
* in the detail area of the expanded notification.
* These calls are ignored by the support library for
* pre-4.1 devices.
*/
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.addAction (R.drawable.ic_stat_dismiss,
getString(R.string.dismiss), piDismiss)
.addAction (R.drawable.ic_stat_snooze,
getString(R.string.snooze), piSnooze);
/*
* Clicking the notification itself displays ResultActivity, which provides
* UI for snoozing or dismissing the notification.
* This is available through either the normal view or big view.
*/
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
startTimer(mMillis);
}
private void issueNotification(NotificationCompat.Builder builder) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Including the notification ID allows you to update the notification later on.
mNotificationManager.notify(CommonConstants.NOTIFICATION_ID, builder.build());
}
private void startTimer(int millis) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_start));
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.sleep_error));
}
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_finished));
issueNotification(builder);
}
}
Intent mServiceIntent = new Intent(context.getApplicationContext(), PingService.class);
mServiceIntent.putExtra(Const.EXTRA_MESSAGE, "" + msg);
mServiceIntent.putExtra(Const.ID, reminder_id);
startService(mServiceIntent);
And passing the data to issueNotification method for Action Button intent like
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
dismissIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
snoozeIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
But i am not getting the ID at the time of Click event of the Action button from issueNotification and passing the intent in onHandleIntent method
It is automatically set to 1 after Notification generation and i am not able to cancel that notification due to wrong notification id set into putExtra of PendingIntent
I am trying with passing different flag like
PendingIntent piDismiss = PendingIntent.getService(this, 0, taken_intent, PendingIntent.FLAG_UPDATE_CURRENT);
Please help me out i am trying it since long time but not getting the correct id.
My putExtra is override with 1 somehow....
Thank you in advnace
After so much reasearching finally got a solution that i need to pass different code in pending intent like
PendingIntent piDismiss = PendingIntent.getBroadcast(this, CommonConstants.NOTIFICATION_ID, dismissIntent, 0);
which is dynamic one and unique one in each Action Button case.
Use Broadcast receiver to achieve this instead of Service ( getBroadcast ).
Thank you.

calling a method in service after click on notification

i have a notification which i'm calling from a service. I want to call the service again on notification click. But the notification click is not able to get inside the method.
Intent intent = new Intent(this, MyService.class).setAction(ACTION_1);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.food)
.setContentTitle("notification")
.setContentText("near by you!");
NotificationManager mNotificationManager =(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Method that i want to call is
if (ACTION_1.equals(resultPendingIntent)) {
getRecommendation();
}
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager.notify(id, mBuilder.build());
i have tried following link but not able to resolve my problem.
How to execute a method by clicking a notification
You can specify a Broadcast in your Service and launch that via a PendingIntent in your notification.
Intent stopIntent = new Intent("my.awersome.string.name");
PendingIntent stopPi = PendingIntent.getBroadcast(this, 4, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Then, in your notification builder:
NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context)
...
.setContentIntent(stopPi);
In your Service you can setup a BroadcastReceiver as:
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Code to run
}
};
You register this receiver in your Service (possibly in onStartCommand()) only using:
registerReceiver(myReceiver, new IntentFilter("my.awersome.string.name"));
Your Service MUST be running for this to work.
Better option is to try How to execute a method by clicking a notification ..but be careful because of the static class

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

How to clear or close notification from notification bar click on close button in android

I use below code how to achieve my motto, I want to close or clear notification from notification bar click on close button
Intent moreNewsIntent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(AppService.this, 0, moreNewsIntent, 0);
// expanded view of the notification.
/* Intent close = new Intent(this, AppService.class);
close.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, close, 0);*/
int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, AppService.this);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setTicker("News Notification")
.setContentText(getString(R.string.lbl_notification_title_news))
.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE)
.setLights(0xff00ff00, 300, 100)
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setContentIntent(pIntent)
.addAction (R.drawable.news_negative,getString(R.string.btn_more_nes), pIntent)
.addAction (R.drawable.close,getString(R.string.btn_close), dismissIntent)
.setAutoCancel(true);
NotificationActivity.java
public class NotificationActivity extends Activity {
public static final String NOTIFICATION_ID = "001";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
finish(); // since finish() is called in onCreate(), onDestroy() will be
// called immediately
}
public static PendingIntent getDismissIntent(int notificationId,
Context context) {
Intent intent = new Intent(context, NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(NOTIFICATION_ID, notificationId);
PendingIntent dismissIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
return dismissIntent;
}
}
AndroidManifest.xml
<activity android:name=".NotificationActivity" android:taskAffinity="" android:excludeFromRecents="true">
Thanx in advance help would be greatly appreciated
Call cancel() with the same id you initialized the notification with.
If you are asking how to get a PendingIntent to do a cancel() call, it looks like you were on the right track with PendingIntent.getService(). A better approach would probably be to use PendingIntent.getBroadcast(), register a receiver in the manifest, and do the call from there.

Categories

Resources