How does one animate the Android sync status icon? - android

I simply want to start and stop the sync icon that is in the status bar. I thought it would be a simple call using NotificationManager, but I cannot find the documentation or sample Q&A on the web or SO.

I found my answer ...
http://libs-for-android.googlecode.com/svn-history/r46/trunk/src/com/google/android/accounts/AbstractSyncService.java
This shows how to set and cancel the stat_notify_sync icon.
private void showNotification(String authority) {
Object service = getSystemService(NOTIFICATION_SERVICE);
NotificationManager notificationManager = (NotificationManager) service;
int icon = android.R.drawable.stat_notify_sync;
String tickerText = null;
long when = 0;
Notification notification = new Notification(icon, tickerText, when);
Context context = this;
CharSequence contentTitle = "mobi"; //createNotificationTitle();
CharSequence contentText = "bob"; //createNotificationText();
PendingIntent contentIntent = createNotificationIntent();
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(mNotificationId, notification);
}
private void cancelNotification() {
Object service = getSystemService(NOTIFICATION_SERVICE);
NotificationManager nm = (NotificationManager) service;
nm.cancel(mNotificationId);
}

To get an animated sync icon you can use android.R.drawable.ic_popup_sync icon. For instance, using the more recent notification builder, you'd use something like:
Notification notification = new NotificationCompat.Builder(mContext)
.setContentTitle("my-title")
.setContentText("Loading...")
.setSmallIcon(android.R.drawable.ic_popup_sync)
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.build();

Thanks for your example, it saved me some time. I created a static method in my Application so I can easily turn the icon on/off from anywhere in my code. I still can't get it to animate though.
In MyApplication.java:
private static Context context;
private static NotificationManager nm;
public void onCreate(){
context = getApplicationContext();
nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
...
}
public static void setNetworkIndicator(boolean state) {
if (state == false) {
nm.cancel(NETWORK_ACTIVITY_ID);
return;
}
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
Notification n = new Notification(android.R.drawable.stat_notify_sync, null, System.currentTimeMillis());
n.setLatestEventInfo(context, "SMR7", "Network Communication", contentIntent);
n.flags |= Notification.FLAG_ONGOING_EVENT;
n.flags |= Notification.FLAG_NO_CLEAR;
nm.notify(NETWORK_ACTIVITY_ID, n);
}
And then from anywhere in my application:
MyApplication.setNetworkIndicator(true);
MyApplication.setNetworkIndicator(false);

Related

Migrate method setLatestEventInfo to API 23+

Currently I'm running with new environment in Android. Unfortunately, previous developer before I joined, it seems he using API 22. So, this is about legacy.
Now I have several issue in Notification, since setLatestEventInfo was removed (for 23+). I face with challenge to migrate past method. Here my code:
/depreciation/
#protected void PushNotification(String title, String message) {
String ns = Context.NOTIFICATION_SERVICE;
int NOTIFICATION_ID = 1;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = message;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = this;
CharSequence contentTitle = title;
CharSequence contentText = message;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.defaults |= Notification.DEFAULT_SOUND;
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
Need suggest to do the right thing, several opinion suggest to adding NotificationCompat but I don't know how to do or any alternative for this?
Try use NotificationCompat.Builder

Make Notification cleared by user or once clicked

I have a service that may show a notification, the problem is once the notification is set, it doesn't clear neither when clicked, nor when swiped on. I am using the flag Notification.FLAG_AUTO_CANCEL but it doesn't seem to do anything..
private NotificationManager nm;
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
private final int NOTIFY_ID = 1;
private void showNotification(String date, String name) {
try{
CharSequence text = "You have new Event";
Notification notification = new Notification(R.drawable.small_icon, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, viewEvents.class).putExtra("date", date), 0);
notification.setLatestEventInfo(this, name, "Date: "+date, contentIntent);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.FLAG_AUTO_CANCEL;
nm.notify(NOTIFY_ID, notification);
}catch(Exception e){
Log.i("Notification",e.toString());
}
}
So what am I doing wrong?
Try using Notification.Builder or NotificationCompat.Builder instead of rolling the Notification manually.
Among other things, this would prevent the bug in your code, where you are applying FLAG_AUTO_CANCEL to defaults rather than flags.
Notification.FLAG_AUTO_CANCEL is commented out in your code.
But in case it isn't then flag Notification.DEFAULT_LIGHTS should be setted in notification.defaults not in notification.flags
I use this code to show/hide notifications:
private Handler handler = new Handler();
private Runnable task = new Runnable() {
#Override
public void run() {
NotificationManager manager = (NotificationManager) contesto.getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(contesto.getApplicationContext(), SearchHistory.class);
PendingIntent contentIntent = PendingIntent.getActivity(contesto.getApplicationContext(), 0, launchIntent, 0);
//Create notification with the time it was fired
NotificationCompat.Builder builder = new NotificationCompat.Builder(contesto);
builder.setSmallIcon(R.drawable.ic_launcher).setTicker("MESSAGE HERE!").setWhen(System.currentTimeMillis()).setAutoCancel(true).setDefaults(Notification.DEFAULT_SOUND).setContentTitle("TITLE").setContentText("MESSAGE").setContentIntent(contentIntent);
Notification note = builder.build();
manager.notify(100, note);
}
};
And to invoke just put:
handler.post(task);

Android notification not working

I've been attempting to get a notification of a successful upload from an ASyncTask to work all day. I'm not getting any errors from my current code but I can't get the notification to show in the notification bar (or anywhere else). I get no messages in LogCat and no notification appears in the Notification bar. This is my code:
Notification mNotification = new Notification(icon, tickerText, when);
CharSequence contentTitle = "upload completed.";
CharSequence contentText = "upload completed.";
Intent notificationIntent = new Intent(context, CastrActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_NO_CREATE);
mNotification.contentIntent = contentIntent;
mNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
This is called from the onPostExecute() method of an ASyncTask. I'm a bit confused on the PendingIntent part, to be honest. Any clarification of what I suspect to be incorrect code there would be greatly appreciated.
Even though your problem is solved, I'll just post how I solved my problem that the notification was not showing, perhaps it might help other people reading the answers:
In my notification building I was missing the icon. As soon as I added something like setSmallIcon(R.drawable.ic_launcher) the notification was shown.
I have created the class to show notifications:
public class NotificationData {
public static NotificationManager mNotificationManager;
public static int SIMPLE_NOTFICATION_ID;
private Context _context;
public NotificationData(Context context) {
_context = context;
}
public void clearNotification() {
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
}
public void SetNotification(int drawable, String msg, String action_string, Class cls) {
mNotificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE);
final Notification notifyDetails = new Notification(drawable, "Post Timer", System.currentTimeMillis());
long[] vibrate = { 100, 100, 200, 300 };
notifyDetails.vibrate = vibrate;
notifyDetails.ledARGB = 0xff00ff00;
notifyDetails.ledOnMS = 300;
notifyDetails.ledOffMS = 1000;
// notifyDetails.number=4;
notifyDetails.defaults =Notification.DEFAULT_ALL;
Context context = _context;
CharSequence contentTitle = msg;
CharSequence contentText = action_string;
Intent notifyIntent = new Intent(context, cls);
// Bundle bundle = new Bundle();
// bundle.putBoolean(AppConfig.IS_NOTIFICATION, true);
notifyIntent.putExtras(bundle);
PendingIntent intent = PendingIntent.getActivity(_context, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
}
How to use this class:
NotificationData notification; //create object
notification = new NotificationData(this);
notification.SetNotification(R.drawable.notification, "Notification Title", "Click to open", YourClassName.class);
Add permission android.permission.VIBRATE
Try this:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.icon; // icon from resources
CharSequence tickerText = "Any thing"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context21 = getApplicationContext(); // application Context
CharSequence contentTitle = "Anything"; // expanded message title
CharSequence contentText = (CharSequence) extras.get("message"); // expanded message text
Intent notificationIntent = new Intent(this, MainStart.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.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
/* long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;
notification.ledARGB = Color.RED;
notification.ledOffMS = 300;
notification.ledOnMS = 300;*/
notification.setLatestEventInfo(context21, contentTitle, contentText, contentIntent);
mNotificationManager.notify(Constants.NOTIFICATION_ID, notification);
Another thing to try is to make sure your manifest contains
<permission android:name="android.permission.STATUS_BAR_SERVICE" android:protectionLevel="signature" />
Also mine seemed to ignore successive notifications with the same NOTIFICATION_ID.
For me this kept happening and I had no idea why but the problem was that the icon I set was too large so it was giving me some random error.

notification bar - how to write text there

I want to know how to write notification text only on the notification bar and different text on the Notification layout?
The accepted answer contains deprecated class and methods. Look at here.
Here is an example using NotificationCompat.Builder to build Notifications :
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.my_drawable_resource)
.setContentTitle("my title")
.setContentText("my content")
.setContentIntent(pendingIntent);
Notification notification = mBuilder.build();
// default phone settings for notifications
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
// cancel notification after click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// show scrolling text on status bar when notification arrives
notification.tickerText = title + "\n" + content;
// notifiy the notification using NotificationManager
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
May help newcomers !
The NotificationCompat.Builder class has method setTicker() that allows you to do that.
int icon = R.drawable.notification_icon; // icon from resources
CharSequence tickerText = "Hello"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = "My notification"; // expanded message title
CharSequence contentText = "Hello World!"; // expanded message text
Intent notificationIntent = new Intent(this, MyClass.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);
you should look at this link......... Click Me
The first text that appears in the notification bar is defined by the setTicker() method.
The text for the title is defined by setContentTitle().
The text for the content is defined by setContentText().
This is an example:
private void showCustomNotification(){
final int NOTIFICATION_ID = 1;
String ns = Context.NOTIFICATION_SERVICE;
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.mipmap.ic_launcher;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, getString(R.string.app_name), when);
notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND; // Sound
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Java (programming language)")
.setTicker("Java (Open to see the info).")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentText("Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented,[14] and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers \"write once, run anywhere\" (WORA),[15] meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.");
// NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

How to show an icon in the status bar when application is running, including in the background?

I want to put an icon in the status bar when ever my application is running, including when it is running in the background. How can I do this?
You should be able to do this with Notification and the NotificationManager. However getting a guaranteed way to know when your application is not running is the hard part.
You can get the basic functionality of what you are desiring by doing something like:
Notification notification = new Notification(R.drawable.your_app_icon,
R.string.name_of_your_app,
System.currentTimeMillis());
notification.flags |= Notification.FLAG_NO_CLEAR
| Notification.FLAG_ONGOING_EVENT;
NotificationManager notifier = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notifier.notify(1, notification);
This code must be somewhere where you are sure will get fired when your application starts. Possibly in your application's custom Application Object's onCreate() method.
However after that things are tricky. The killing of the application can happen at anytime. So you can try to put something in the onTerminate() of the Application class too, but it's not guaranteed to be called.
((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
will be what is needed to remove the icon.
For new API you can use NotificationCompat.Builder -
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title");
Intent resultIntent = new Intent(this, MyActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(NOTIFICATION_ID, notification);
It will show as long as your application is running and someone manually closes your application. You can always cancel your notification by calling -
mNotifyMgr.cancel(NOTIFICATION_ID);
Take a look at the Dev Guide "Creating Status Bar Notifications".
One way to achieve the goal of keeping the icon there only when the application is running is to initialize the notification in onCreate() and call cancel(int) in your onPause() method only if isFinishing() returns true.
An example:
private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notificationManager.notify(NOTIFICATION_EX, notification);
}
#Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
notificationManager.cancel(NOTIFICATION_EX);
}
}
It really works.
I created a method out of the example above:
private void applyStatusBar(String iconTitle, int notificationId) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(iconTitle);
Intent resultIntent = new Intent(this, ActMain.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notificationId, notification);}
It should be called like: applyStatusBar("Statusbar Test", 10);

Categories

Resources