0

I have sync adapter that performs some operation in background. To notify my main activity about sync operation status, I used broadcast receivers, so my activity is able to receive messages from sync adapter. It works fine. However, I also need to display notification on android status bar, that indicates some sync results.

So I wrote simple method reponsible to disaply system notification:

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

Then, above method is called in onPerform sync:

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

Context is retrieved from constructor. It works without any problems, notification is showing.

However I also need to show main activity after user cicks on notification. So I believe I need to create PendingIntent and pass it to my notification builder (as it's commented in my code). But to pass main activity object to my sync adapter? Notification can be also displayed after auto sync finished.

Any tips?

user1209216
  • 7,404
  • 12
  • 60
  • 123
  • If you show a notification a user has to be able to interact with it ea opening the app, else showing the notification is not useful and doesn't have to be shown at all. – Aegis Jan 06 '16 at 16:15

1 Answers1

0

So, I figured it out. Solution is to create pending intent this way:

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

So after user clicks to notification, main activity will be shown.

user1209216
  • 7,404
  • 12
  • 60
  • 123