Could anyone possibly offer some advice on how to setup Status bar notifications in Android?
My skillset is all based around design/front-end dev (hence using phonegap) so I'm a beginner with Eclipse.
I have read this tutorial - http://androidforbeginners.blogspot.com/2010/02/how-to-create-status-bar-notifications.html and have pasted the code into the activity area of my Android Manifest file. But I don't quite understand how it will work. If I compile this now as an APK and install it on a phone -- is it now ready to receive notifications? If so how do I send them, and where do I type the sending code?
Hopefully it's fairly simple as my boss is hoping that I'll have it completed before christmas!
Cheers for your help.
All the best
Paul
You want status bar notification? If yes...you are lucky...here's a plugin which I already created for phonegap. Look around for how to embed the external plugin in android.
https://github.com/phonegap/phonegap-plugins/tree/master/Android/StatusBarNotification
Here you can find better explanation with source codes about notifications.
Notification can be a reaction on some event. For instance, you can develop a simple application with one button. When you press this button a notification will be displayed in the status bar.
About the development. You should install Android SDK, create an emulator of the device. Also it is very useful to install Android ADT - this is a pluging for Eclipse to help to develop Android applications. After that when you build an application it will be automatically installed on the emulator.
Here is the code how to make a simple notification:
package your.package
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AcNotificationTestMain extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private static final int SEND_ID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mBtnSend = (Button) findViewById(R.id.button1);
mBtnSend.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Log.v("","OnClick...");
// Create an object of Notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.sym_action_email; // icon from resources
CharSequence tickerText = "New Notification"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = "My notification"; // expanded message title
CharSequence contentText = "Click me!"; // expanded message text
Intent notificationIntent = new Intent(this, AcNotificationTestMain.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 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(SEND_ID, notification);
}
}
And layout file:
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="#string/hello"/>
<Button android:id="#+id/button1" android:text="#string/AcNotificationTest_BtnSendNotificationText" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
Related
I would greatly appreciate any help with troubleshooting my use of notifications within the Android emulator. I have tried several different versions without success and the code below seems to distill the needed elements down to the minimum. The problem is that the notification simply doesn't get sent. I hear the "click" noise when I tap the button in the emulator but nothing else.
I had read somewhere that having the wrong type of image may cause problems and I have tried several. The one I have included now is generated using Vector Asset within the res folder. It feels like there is something simple that I am missing but from what I can see from all the examples I have found online the basic elements are sound.
Any help or direction would be appreciated.
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int idNumber = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
public void sendNotification(View view){
notification.setSmallIcon(R.drawable.ic_android_black_24dp);
notification.setContentText("This is the notification message");
notification.setContentTitle("Notification");
notification.setTicker("There is a notification");
notification.setWhen(System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(idNumber, notification.build());
}
}
I'm using Worklight Push Notification but on Android the push comes with no sound. I want to enable default sound (and LED if possible).
I'm using the sample push notification example code.
var notification = WL.Server.createDefaultNotification(notificationText, badgeDigit, {custom:"data"});
I also tried to assigning a value like notification.GCM.sound = "true" or notification.GCM.sound = "default" but it is playing continuous sound on some devices.
To accomplish this you will have to modify your app. Worklight will generate a skeleton class in your Android project, GCMIntentService.java
In order to add sound and flash the LED notification light, you will have to override the notify methods in the GCMIntentService class. Your file will look like this:
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
public class GCMIntentService extends
com.worklight.androidgap.push.GCMIntentService {
#Override
public void notify(Context context, String alert, int badge, String sound,
Intent intent) {
super.notify(context, alert, badge, sound, intent);
// call helper method
notifyLightAndSound(context);
}
#Override
public void notify(Context context, String tickerText) {
super.notify(context, tickerText);
// call helper method
notifyLightAndSound(context);
}
private void notifyLightAndSound(Context context) {
// Get the default notification sound
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// build a notification with the light and sound
// LED will be on for 1000 ms and off for 800 ms until you turn on your
// screen
Notification n = new Notification.Builder(context)
.setLights(Notification.DEFAULT_LIGHTS, 1000, 800)
.setSound(notification).build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// play sound and flash LED
mNotificationManager.notify(4, n);
}
}
This will flash the LED and play the default notification sound of your phone "different based on each phone".
I hope this helps to answer your question.
LED notification is not available.
See here: Led not working on Android using Unified Push Notification of worklight (6.0.0.2)
To use a custom notification sound (see supported media formats):
If the folder does not exist already, add a folder named raw under the existing native\res folder in yourProject\apps\yourApp\android\native
Place the sound file in the raw folder
To use default notification sound, try sending it empty:
notification.GCM.sound = "";
I am developing for Honeycomb and for days i am trying to solve this problem.
I have an notification service without intent (don`t need one), the problem is that after every call for displaymessage function the notification pup-up each time, so i get 100 notifications. I would like it to popup only once and after that only change the text of percent. Similar to downloading from market progress bar and percentage. I have isolated the function and created new testing code but with no success. If you look at this from other angle, i wish to change the text on existing notification without creating new notification.
Can you please help me?
Here is the whole code (after the isolation):
package com.disp;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.SystemClock;
public class DispalyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 100; i++) {
SystemClock.sleep(300);
displaymessage(""+i+"%");
}
}
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
Notification notification = new Notification(R.drawable.ic_launcher, "Notification Service", System.currentTimeMillis());
Context context = getApplicationContext();
notification.setLatestEventInfo(context, "Downloading Content:", string, null);
final int HELLO_ID = 2;
mNotificationManager.notify(HELLO_ID, notification);
}
}
Because each notification is uniquely identified by the NotificationManager with an integer ID, you can revise the notification by calling setLatestEventInfo() with new values, change some field values of the notification, and then call notify() again.
You can revise each property with the object member fields (except for the Context and the notification title and text). You should always revise the text message when you update the notification by calling setLatestEventInfo() with new values for contentTitle and contentText. Then call notify() to update the notification. (Of course, if you've created a custom notification layout, then updating these title and text values has no effect.)
from
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
I know, there are tons of these on here, but I've been trying solutions all day and haven't gotten anywhere.
Neither the example on google's docs, nor any of the 5 other ways I've found on here have worked for me at all.
As is the typical case, when I click the notification it closes the status bar and nothing new is shown onscreen.
I am creating the notification from a service and need the notification to trigger a new activity that has not yet been created.
I also will need a way to pass information to that activity via intent.
And yes... this is java for Android
What follows are the shattered remnants of my code.
package com.bobbb.hwk2;
import java.io.FileOutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.widget.Toast;
public class contactBackup extends Service
{
private NotificationManager nManager;
private static final int NOTIFY_ID = 1100;
#Override
public void onCreate()
{
super.onCreate();
String ns = Context.NOTIFICATION_SERVICE;
nManager = (NotificationManager)getSystemService(ns);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// inform user that service has started
Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show();
String data = lookUpContacts();
if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) )
{
Context context = getApplicationContext();
// create the statusbar notification
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
//nIntent.putExtra("data",data);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
}
}
#Override
public void onDestroy()
{
nManager.cancel(NOTIFY_ID);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
// function returns string containing information
// from contacts
public String lookUpContacts()
{
...
}
public boolean saveToSDCard(String fileName, String data)
{
...
}
}
I can only hope that whatever is causing my problem is something fixable and not more of the crazy glitches I've been getting with eclipse (which no one else seems to have ever seen >:U )
If you can help me solve this problem, please share.
If you can't help with this specific problem but feel obligated to say unrelated things about posting, styles, topics, or good practice, then DON'T
Thank you :D
Edit:
You're going to have to add a flag for FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is because you're launching from outside your app (from the system notification bar).
This is what happens when people overwork themselves. XD
The only reason none of the tutorials I tired worked is because I misspelled my activity name in the manifest.
Thanks for stopping by
Just add following in contactBackup(service class),
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
nIntent.putExtra("data",data);
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
then get value in contactViewer class,
as,
String s=getIntent().getStringExtra("data");
Suppose I am creating an Android application that's like an SMS app. The requirements are as follows:
The user can receive multiple notifications, each one having a dynamic ID of type int.
When a notification is selected, it loads an activity which displays a corresponding message (the SMS).
The single notification that was selected should be automatically dismissed.
My idea for how to handle this was to use putExtra to add the integer ID to the intent, which would then be accessible from the intent within the activity it loads, which would then dismiss the notification that called it.
For my test case, here are the specs:
Notifications will eventually be
generated from a service, for now
they are being spawned when the test
user presses a button.
When a notification is selected, the
called activity toasts the message,
then attempts to dismiss the
notification. (For the sake of
visibility)
Here are my problems:
When the first notification is
selected, it is correct. The
notification is dismissed.
When each successive notification is
selected, the first notification's
ID is shown, and nothing is
dismissed.
I am a Java novice, more accustomed
to scripting languages (such as
Perl, PHP, etc) :)
Here is my source:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
>
<Button
android:id="#+id/create_notification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text = "Create new notification"
/>
package org.test.notifydemo;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class aRunNotificationDemo extends Activity
{
private NotificationManager mNotificationManager;
#Override
public void onCreate( Bundle icicle )
{
super.onCreate( icicle );
setContentView( R.layout.run_notify_demo );
mNotificationManager = (NotificationManager) getSystemService( aRunNotificationDemo.NOTIFICATION_SERVICE );
int close_notify_id = getIntent().getIntExtra( "notification_id", 0 );
if ( close_notify_id != 0 )
{
Toast.makeText( aRunNotificationDemo.this, "Dimissing this notification: " + Integer.toString(close_notify_id), Toast.LENGTH_SHORT ).show();
mNotificationManager.cancel( close_notify_id );
}
findViewById( R.id.create_notification ).setOnClickListener( new MyButtonListener() );
}
private class MyButtonListener implements Button.OnClickListener
{
public void onClick( View my_view )
{
Random randGen = new Random();
int notify_id = randGen.nextInt();
int icon = R.drawable.icon_notification_01;
CharSequence tickerText = Integer.toString(notify_id) + " New SMS!";
long when = System.currentTimeMillis();
Notification my_notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = Integer.toString(notify_id) + " New SMS Available!";
CharSequence contentText = Integer.toString(notify_id) + " There is a new SMS available.";
Intent notificationIntent = new Intent( aRunNotificationDemo.this, aRunNotificationDemo.class );
notificationIntent.putExtra( "notification_id", notify_id );
PendingIntent contentIntent = PendingIntent.getActivity( aRunNotificationDemo.this, 0, notificationIntent, 0 );
my_notification.setLatestEventInfo( context, contentTitle, contentText, contentIntent );
mNotificationManager.notify( notify_id, my_notification );
}
}
}
When activity is once created its onCreate() method is called. Next time it is displayed the method is not necessarily called. Try moving code which removes the notification to onResume() method. Get familiar with Activity life cycle.
And by the way it is easier than you think:
http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL
my_notification.flags |= Notification.FLAG_AUTO_CANCEL;
Put the code above when creating a Notification.