mercredi 24 août 2016

How to modularize a (NotificationManager) library for Android?

I have a customized MyNotificationManager im my app (package com.ralfi.myapp.mynotifier;), which works so far. I would like to extract this mynotifier package as a single *.aar library, which in turn I can import to all my other apps and use it there.

package com.ralfi.mynotifiier;
class MyNotificationManager {
 Context context;
 NotificationManager notificationManager;

 public class MyNotificationManager(Context context) {
     this.context = context;
     mNotificationManager = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
 }

 //..
public void sendNotification(NotificationCompat.Builder builder) {
    Intent notificationIntent = new Intent(this.context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent notificationPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationManager.notify(0, builder.build());
}
}

I would instantiate it in my android app project and make ist static availabe for any other classes in there.

import com.ralfi.mynotifiier.MyNotificationManager; // e.g.: delivered in a *.aar

class MyRootApplication
  //..
  private static MyNotificationManager myNotificationManager;
  //..
  void onCreate(){
    myNotificationManager = new MyNotificationManager(context);
    //..
  }

  public static AppNotificationManager getAppNotificationManager() {
    return appNotificationManager; 
  }
}

Main Question: As you can see in MyNotificationManager.sendNotification() I need the MainActivity.class as a parameter for Intent constructor and the X.addParentStack() method. When I intent to deliver the MyNotificationManager as a *.aar library, I would not know then, what this MainActivity would be called in the Android App project? How can I make this generic?

Side Question: Is that the proper way to use it any class in the final project by calling MyRootApplication.getAppNotificationManager().sendNotification(...)? Are there maybe ay better design patterns? (Dependecy Injection?)

Aucun commentaire:

Enregistrer un commentaire