notification opening a new window no matter what in Java Android - java

I want to launch a notification. When I click on it, it opens a NEW window of the app.
Here's my code:
public class Noficitation extends Activity {
NotificationManager nm;
static final int uniqueID = 1394885;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent= new Intent (Intent.ACTION_MAIN);
intent.setClass(getApplicationContext(), SchoolBlichActivity.class);
PendingIntent pi=PendingIntent.getActivity(this, 0, intent, 0);
String body = " body";
String title = "title!";
Notification n =new Notification(R.drawable.table, body, System.currentTimeMillis());
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(uniqueID,n);
finish();
}
by the way, if i add nm.cancel(uniqueID) before the finish(), it creates the notification and immediately deletes it...
Thanks for the help :D

You might want to just add a notification in the notification bar, and when the user clicks it, it will launch the actual Activity. This way the user won't be interrupted in whatever he's doing.
Create the status bar notification like this:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Hello", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, myclass.class);
notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello world!", notificationIntent, PendingIntent.getActivity(this, 0, notificationIntent, 0));
mNotificationManager.notify(1, notification);
http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Are you just trying to open a notification window in a current activity? Because if you are I dont think you need to launch it with an intent. You normally only use intents to launch new services or activities in your app unless youve built a custom view and activity/service which is to take place within the notification box. I see you have it set up in its own class which is fine but I think the way your doing it by default would open an entire new view.
If you need to launch a notification during a process or something like a button click you dont need to have the intent there.....or at least I never did :) What exactly are you trying to achieve with the notification.

Related

Update Notification with a Button click

I just a newbie of Android, while I programming I had the problem that is about the Notification.
I need your help to process updating notification.
The context of this like when you are playing the game and you had a notification about another game (the second game is running in the background). Then you have a new notification of the second game which has the same ID of the previous notification.
This is my declaration:
I used NotificationManagerclass to create a Notification.
private NotificationManager manager;
private int notiId = 6789; // Each notification will be managed by an ID
private int numMsg = 0;
This is the function clickToSend button:
public void clickToSend(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Setting Notification Properties
builder.setContentTitle("New Message");
builder.setContentText("Notification Demo: Message has received");
builder.setTicker("Message Alert");
builder.setSmallIcon(R.drawable.ic_action_unread);
builder.setNumber(++numMsg);
Intent intent = new Intent(this, NotificationDetailActivity.class);
TaskStackBuilder stack = TaskStackBuilder.create(this);
stack.addNextIntent(intent);
PendingIntent pendingIntent = stack.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notiId, builder.build());
}
I think code of function clickToUpdate that will process like the clickToSend function.
Thanks for your help!
My language is not good. I'm sorry for the inconvenience.

How to make a button in a notification 'do something'

I am trying to make a simple stopwatch app that will display the time in a notification and give you a couple buttons that will allow you to start and stop the stopwatch.
How do I add a button to a notification? And how do I 'point' that button to a certain function?
Heres a picture of what I was thinking:
actionIntent = new Intent(this, MainActivity.class);
actionPendingIntent = PendingIntent.getService(this, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
timerNotification.addAction(android.R.drawable.ic_media_pause, "Start", actionPendingIntent);
This is what I currently have. Where in the intent would I put the function I want to execute?
Add Action to the notification and assign a pendingintent
If you want to custom your notification layout,you can use setContent() function with a RemoteViews of your custom layout.
Remote View mRemoteView = new RemoteViews(getPackageName(), R.layout.notification_general);
Notification.Builder mBuilder = new Notification.Builder(context);
mBuilder.setSmallIcon(R.mipmap.ic_battery)
.setContent(mRemoteView)
.setContentIntent(notificationPendingIntent);
mNotificationManager.notify(1, mBuilder.build());
To handle an notification button onClick event, you need to use separate PendingIntents(made from Intents with differecnt actions) for every button. Later in onReceive() you just check action of incoming Intent & execute different code depending on that. Remember to assign your Listener on manifest.
Intent generalIntent = new Intent(context, GeneralReceiver.class);
generalIntent.putExtra(REQUEST_CODE, ACTION_GENERAL);
PendingIntent generalPendingIntent =
PendingIntent.getBroadcast(context, 1, generalIntent, 0);
mRemoteView.setOnClickPendingIntent(R.id.btnNotificationGeneral, generalPendingIntent);
public static class GeneralReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Your code here
}
}

Using PendingIntent to reach my method

I have an android App that makes notifications. I can generate a notification together with a button, without a problem. My problem is the button's action. I want the button to call a method, for example a text-printing method. I'm using addAction(icon, "title", pendingIntent).
public void sendNotification(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context.getApplicationContext(), SomeClass.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
// This creates the button and it is using a pending intent.
.addAction(R.drawable.icon, "Print something", printPendingIntent)
// Clicking on notification takes you back to the App.
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentTitle("My Title")
.setContentText("Some text");
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
So the problem is in printPendingIntent, (no code written as you can see),
how do I access / call a method by using this pending intent?
Thanks for answers and sorry if the question is not clear and detailed enough.
add intent.putExtra("key","printmethod"); then receive the data in your SomeClass using getIntent().getExtras("Key"); if the value is matched then you can call your desired method in that activity.

How to have a notification open a view within an activity?

Right now I have an alarm on my main activity which launches a class which launches a notification on the status bar. When I click on the notification, it opens up my main activity, now I want it to open a n specific view within that activity.
This is my notification code.
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
int icon = android.R.drawable.stat_notify_chat; // icon from resources
CharSequence tickerText = "TickerText"; // ticker-text
long when = System.currentTimeMillis(); // notification time
CharSequence contentTitle = "My notification"; // message title
CharSequence contentText = "Hello World!"; // message text
//This is the intent to open my main activity when the notification is clicked
final Intent notificationIntent = new Intent(context, mainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(notifID, notification);
This is the button in the layout used by my main activity which opens the view I want the notification to open (graph view).
<Button
android:id="#+id/graphsButton"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_below="#id/reviewButton"
android:layout_toRightOf="#id/medicineButton"
android:onClick="openGraphs"
android:text="Graphs" />
When you click on the button. It executes the following method in the main class.
public void openGraphs(View v) {
canExit = false;
setContentView(R.layout.graphs);
}
So basically, I got the notification to open the app and launch the main activity, but I want it to launch the graph view directly.
Can anybody help me?
You could add a flag to the pending intent set in the notification using the intent's extras. Evaluate the intent when the activity is started. If you find the flag in the starting intent execute the the code in openGraphs(). Make sure to get the most recent intent (not the one which may have started the activity earlier, here is some advice on that: https://stackoverflow.com/a/6838082/1127492).
Is there anything stopping you from showing the graph directly in the Activity?
In the above Activity instead of having a button, to show the Graph when clicked, directly set the view to R.layout.graphs in onCreate() method.
In case you have the prescribed activity for some other purpose then create a separate activity just to show the graph and point to it from the notificationIntent.

Notification Intents not working for Android application

My app is running a service that collects feeds. When it find these feeds it create notations (unsuccessfully). I use a method call like this:
doNotification(date,"New Article",title,link,content,description,false);
for articles and this:
doNotification(date,"New Video",title,link,"","",true);
for videos. The method is this:
public void doNotification(Date date,String title,String subtext,String url,String body,String dateString,boolean video){
long time = date.getTime();
if(time > feedGetter.lastFeed){
//New feed, do notification
NotificationManager mNotificationManager = (NotificationManager) feedGetter.service.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
Notification notification = new Notification(icon, title + ": " + subtext, time);
Intent notificationIntent = new Intent(feedGetter.service, NotificationActivity.class);
notificationIntent.putExtra("url",url);
notificationIntent.putExtra("video",video);
if(!video){
notificationIntent.putExtra("body",body);
notificationIntent.putExtra("date",dateString);
notificationIntent.putExtra("title",subtext);
}
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(feedGetter.service, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(feedGetter.service.getApplicationContext(), title, subtext, contentIntent);
mNotificationManager.cancel(video? 1 : 0);
mNotificationManager.notify(video? 1 : 0, notification);
//Update new time if necessary.
if(time > feedGetter.newTime){
feedGetter.newTime = time; //New time will be the time for this feed as it is the latest so far
}
}
}
As you see I add some data to the intent so I can handle the notifications correctly. The notifications are assigned to an ID for videos or an ID for articles and should replace the previous notifications. Here is the NotificationActivity that handles the notifications:
public class NotificationActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Debug.out("Notification Activity");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(getIntent().getBooleanExtra("video", true)){
//Handle video notification
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getIntent().getStringExtra("url")));
startActivity(browserIntent);
mNotificationManager.cancel(1);
}else{
//Start application UI and move to article
Intent intent = new Intent(this,TheLibertyPortalActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("url", getIntent().getStringExtra("url"));
intent.putExtra("body", getIntent().getStringExtra("body"));
intent.putExtra("date", getIntent().getStringExtra("date"));
intent.putExtra("title", getIntent().getStringExtra("title"));
startActivity(intent);
mNotificationManager.cancel(0);
}
finish();
}
}
So it's supposed to activate a URL for the videos and restart the application for articles with some data for handling the articles so the article is displayed to the user.
Seems simple enough but it doesn't work. The notifications display and they replace each other on the notification menu, showing the latest notifications for videos and articles but when I click on them they go wrong. I try to click on the article notification and it thinks it is a video and loads one of the videos. I go back onto the notification menu and the video notification has disappeared even when I clicked on the article notification. I try clicking on the article notification and nothing happens. It literally closes the menu and doesn't nothing and the notification remains in the menu doing nothing.
Thank you for any help with this. I am targeting the Google APIs level 14 API, with a min SDK version of level 8, trying with a 2.2.1 Android tablet.
The problem is with the Pending intent. Even though the docs say the requestCode is not used, it is. You must pass a unique integer for each PendingIntent. That worked!

Categories