如何使Android同步状态图标动起来?

7

我只想启动和停止状态栏中的同步图标。我以为使用NotificationManager会很简单,但我在网上或SO上找不到相关文档或示例Q&A。

3个回答

6
我找到了答案...
这里展示了如何设置和取消stat_notify_sync图标。 http://libs-for-android.googlecode.com/svn-history/r46/trunk/src/com/google/android/accounts/AbstractSyncService.java
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);
}

@Haraldo -- 很好的发现。我找到了一个替代链接,希望它将永久有效。 - mobibob

6
为了获得一个具有动画效果的同步标志,您可以使用android.R.drawable.ic_popup_sync图标。例如,使用较新的通知构建器,您可以这样使用:
Notification notification = new NotificationCompat.Builder(mContext)
        .setContentTitle("my-title")
        .setContentText("Loading...")
        .setSmallIcon(android.R.drawable.ic_popup_sync)
        .setWhen(System.currentTimeMillis())
        .setOngoing(true)
.build();

4

感谢您的示例,它为我节省了一些时间。我在我的应用程序中创建了一个静态方法,因此我可以在代码的任何地方轻松地打开/关闭图标。不过,我仍然无法让它动画化。

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

然后在我的应用程序的任何地方:

MyApplication.setNetworkIndicator(true);

MyApplication.setNetworkIndicator(false);

我喜欢你在这个解决方案中的整理风格。 - mobibob
@NicoGranelli -- NETWORK_ACTIVITY_ID是我用来识别状态标志的唯一ID。由于它在您的命名空间中,您可以将其设置为任何值。 - mobibob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接