2016-01-06 45 views
0

我有在后台执行某些操作的同步适配器。为了通知我的主要活动同步操作状态,我使用了广播接收器,所以我的活动能够从同步适配器接收消息。它工作正常。不过,我也需要在android状态栏上显示通知,指示一些同步结果。来自SyncAdapter的系统通知:onPerformSync

所以我写简单的方法reponsible到disaply系统通知:

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同步:

@Override 
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) 
    { 
     ................. 
     sendNotification(context, message); 
    } 

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

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

任何提示?

+0

如果您显示通知,用户必须能够与应用程序进行交互以打开应用程序,否则显示通知无用,并且不必显示。 – Aegis

回答

0

所以,我明白了。解决方法是通过这种方式创建未决意图:

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

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