来自SyncAdapter的系统通知:onPerformSync

时间:2016-01-06 16:02:56

标签: java android android-pendingintent android-syncadapter

我有同步适配器,可以在后台执行某些操作。为了通知我的主要活动有关同步操作状态,我使用了广播接收器,因此我的活动能够从同步适配器接收消息。它工作正常。但是,我还需要在android状态栏上显示通知,这表示一些同步结果。

所以我写了一个简单的方法来消除系统通知:

private void sendNotification(Context ctx, String message)
    {
        Intent intent = new Intent(ctx, this.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Mobile Shopping")
                .setContentText(message)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS)
                .setLights(0xff00ff00, 300, 100)
                .setPriority(Notification.PRIORITY_DEFAULT);
                //.setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 , notificationBuilder.build());
    }

然后,在onPerform sync:

中调用上面的方法
 @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
    {
      .................
      sendNotification(context, message);
    }

从构造函数中检索上下文。它没有任何问题,通知显示。

但是,我还需要在用户提示通知后显示主要活动。所以我相信我需要创建PendingIntent并将其传递给我的通知构建器(因为它在我的代码中被注释)。但是要将主要活动对象传递给我的同步适配器?自动同步完成后也可以显示通知。

任何提示?

1 个答案:

答案 0 :(得分:0)

所以,我明白了。解决方案是以这种方式创建待定意图:

Intent notificationIntent = new Intent(ctx, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);

因此,在用户点击通知后,将显示主要活动。