How does one animate the Android sync status icon?
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 开发者_StackOverflow中文版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);
精彩评论