Monday 8 February 2016

iOs style Badge Icon in android App using Xamarin


Here I'm going to describe how can you add badge icon on application's icon in android device using Xamarin.

Though there is no universal way of implement in all device is available, still some manufacturers support adding a badge on applications icon. And there are a lot of ways available for implementing that is android.

But here I wanted to achieve that by using Xamarin so I have rewrite the android code in C# and here I'm going to share that information.

So following are steps for it.

1.)  So here first step is to add permission in AndroidMenifest file in Droid project. Since different merchants has different permission for the badge implementation, here I'm going to add all the available permission.



2.) Second Step is to create a abstract class,



3.) The next step is to implement the previously created abstract classes that will actually check if launchers are appropriate and update badge on application's icon. Here is sample for Samsung Device.


I have attached all possible implementation for other devices and attached a file for it.

4.) Next step is to to create a method to get supported launcher and for that we need to find supported launcher in device and compare with all implemented launchers.


5.) And then actually call "executeBadge" with count that you want to set,

Here I have attached the file where you can download demo application.
https://drive.google.com/file/d/0B0dJLMU9SXZHemx5bzlPLTlPbXVoX0ZYQ0xtOVdiMVZfT1Nv/view?usp=sharing


Let me know if you find any issue in it or want to rectify any information.

References :
http://vardhan-justlikethat.blogspot.in/2014/07/android-ios-style-badge-app-icon-for.html
https://github.com/leolin310148/ShortcutBadger

48 comments:

  1. Thanks for the article, I'm trying to achieve the same thing. Can you please share the source code for this? I can't find it anywhere in your post.

    ReplyDelete
  2. I have updated the blog and added link where you can download demo application.

    Let me know if there is any problem

    ReplyDelete
  3. Thanks you so much! it worked really well for me! will you keep this article updated for future implementations of badge for other manufacturers?

    ReplyDelete
  4. It worked. Thanks you for good article.

    ReplyDelete
    Replies
    1. BADGERS - I have problem with it. What's BADGER, because i have a foreach - var badgeclass in BADGERS, but fires an erro in design time.

      Delete
  5. Can we have the similar way for LG manufacturers like Nexus devices
    ?

    ReplyDelete
    Replies
    1. Does it have the functionality in major apps like whatsapp and facebook?

      Delete
  6. Hi Hetal, I'm pretty new to Xamarin forms, and now I'm adventuring in its Android part.
    I was able to understand what you did. But maybe you can help me furthermore.
    I implemented to receive notifications. How can I send info from the ListenerService to the MainActivity where I got the instance of the Badge?

    ReplyDelete
    Replies
    1. You just need to call the method from the listener service to update the badge

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Hetal, where do i create an abstract class? In android or pcl project? In example above you say that this example is for samsung. And LG, Sony, Asus, how can i do?

    ReplyDelete
    Replies
    1. It should be in android.

      Here is the demo code I have generated.

      https://drive.google.com/file/d/0B0dJLMU9SXZHemx5bzlPLTlPbXVoX0ZYQ0xtOVdiMVZfT1Nv/view

      Let me know if you face any other issue.

      Delete
  9. I downloaded this example, but i have doubt about it. I have an App and how can i do to implement in my App? In your example, you created with Tab and i'm having difficult to implement in my app. I'm trying to fit to my code but i'm not getting to do. My App work this way. Seller require a discount, then send a notification. There are 7 store and each store many sellers. So the App will be receive many notifications. I need a badge to show how many message there are.

    ReplyDelete
    Replies
    1. You just need to add all this files into Android project as there is in demo.

      And to update the badge count, I have created a Service in droid.

      [Service (Name = "com.xyz") ]

      public class NotificationService : IntentService

      {

      const string packagename = "com.xyz";



      protected override void OnHandleIntent(Intent intent)

      {



      Android.Util.Log.Info("CHECK", "NotificationService");



      // The manufacturer of the product/hardware.



      int badgeno = intent.GetIntExtra("Countvalue",0);

      Badge badge = new Badge (this);

      badge.count (badgeno);



      }

      }


      Now to call this and update the notification count,

      I call this service every time when notification arrives in Droid project in GCM like this,

      Intent ServiceIntent = new Intent(this, typeof(NotificationService));

      ServiceIntent.PutExtra("Countvalue",Settings.UnReadNotification);

      Delete
    2. You can use any other method to update the badge as well this demo only provide the flow I have followed.

      Delete
  10. First, thank you for help me! Thank you very much. I read your example many time and now i'm uderstanding. In exampe above work for samsung only? How do i implement for others? My xamarin is bad and my english too.

    ReplyDelete
  11. The code is for 11 different manufacturers however I have only test the code in Samsung and Sony devices.

    ReplyDelete
  12. This method "public MyBadge getBadger(Context context)" do i implement inside of SamsungHomeBadger? Because it doesn't recognise BADGER, DefaultBadger and context.PackageManager.ResolverActivity

    ReplyDelete
    Replies
    1. Can i comment these lines? Or that method isn't necessary?

      Delete
    2. No it's used to identify the supported device

      Delete
  13. I went to implement the service and i encountered an error in this line: Badge badge = new Badge(this). The error is Badge, what's namespace do i use?

    ReplyDelete
    Replies
    1. It's the class you should have created so just need to reference the that part of namespace

      Delete
  14. What plugin is used? Xam.Plugin.Badge or other?

    ReplyDelete
  15. The service isn't compiling because there is an error. The compiler doesn't recognise Badge, maybe miss reference

    ReplyDelete
    Replies
    1. There is no external plugin used.

      Can you provide me your demo code?

      Delete
    2. yes, how do i send to you?

      Delete
    3. Can you send your full source code to my email id it's
      hetal.h.jariwala@gmail.com

      Delete
    4. I put in your blog the class, but if you need all project is too big to send by email.

      Delete
    5. I uploaded my PCL and Droid project and i shared with you. Thanks for all help.

      Delete
  16. Is it difficult to do work my badge. Lack knowledge for me. I have an issue here, an issue there. If i implement this(badge) my App is finished, i'm trying for almost 3 days and i don't reach success yet.

    ReplyDelete
  17. MyBadge class
    public abstract class MyBadge
    {
    public static MyBadge mBadge;
    protected static Context mContext;
    public static string LOG_TAG = "BadgeImplementation";
    public abstract void executeBadge(int badgeCount);
    public abstract List getSupportLaunchers();

    public MyBadge(Context context)
    {
    mContext = context;
    }
    protected String getEntryActivityName()
    {
    ComponentName componentName = mContext.PackageManager.GetLaunchIntentForPackage
    (mContext.PackageName).Component;

    return componentName.ClassName;
    }
    protected String getContextPackageName()
    {
    return mContext.PackageName;
    }
    }

    ReplyDelete
  18. HomeBadge, i removed Samsung name
    public class HomeBadger : MyBadge
    {
    private static String INTENT_ACTION = "content://com.sec.badge/apps";
    private static String INTENT_EXTRA_BADGE_COUNT = "badgecount";
    private static String INTENT_EXTRA_PACKAGENAME = "package";
    private static String INTENT_EXTRA_ACTIVITY_NAME = "class";

    public HomeBadger(Context context)
    : base(context)
    { }

    public override void executeBadge(int badgeCount)
    {
    try
    {
    ContentResolver localContentResolver = mContext.ContentResolver;
    Android.Net.Uri localUri = Android.Net.Uri.Parse(INTENT_ACTION);
    ContentValues localContentValues = new ContentValues();
    localContentValues.Put(INTENT_EXTRA_PACKAGENAME, getContextPackageName());
    localContentValues.Put(INTENT_EXTRA_ACTIVITY_NAME, getEntryActivityName());
    localContentValues.Put(INTENT_EXTRA_BADGE_COUNT, badgeCount);
    string str = "package=? AND Class=?";
    String[] arrayOfString = new String[2];

    arrayOfString[0] = getContextPackageName();
    arrayOfString[1] = getEntryActivityName();

    int update = localContentResolver.Update(localUri, localContentValues, str, arrayOfString);
    if (update == 0)
    {
    localContentResolver.Insert(localUri, localContentValues);
    }
    }
    catch (Exception localException)
    {
    Android.Util.Log.Error("Check", "Samsung : " + localException.Message);
    }
    }


    public override List getSupportLaunchers()
    {
    List supportLaunchers = new List();
    supportLaunchers.Add("com.sec.android.app.llauncher");
    supportLaunchers.Add("com.sec.android.app.twlauncher");

    return supportLaunchers;
    }

    public MyBadge getBadger(Context context)
    {
    if (mBadge != null)
    {
    return mBadge;
    }
    Log.Debug(LOG_TAG, "Finding badger");
    try
    {
    Intent intent = new Intent(Intent.ActionMain);
    intent.AddCategory(Intent.CategoryHome);
    //ResolveInfo resolveInfo = context.PackageManager.ResolverActivity(intent, PackageInfoFlags.MatchDefaultOnly);
    //String currentHomePackage = resolveInfo.ActivityInfo.PackageName.ToLower();

    //foreach (string badgeclass in BADGERS)
    //{
    // Type t = Type.GetType("PayCaddy.Droid." + badgeclass);
    // MyBadge myObject = (MyBadge)Activator.CreateInstance(t, new Object[] { context });
    // if (myObject.getSupportLaunchers().Contains(currentHomePackage))
    // {
    // mBadge = myObject;
    // }
    //}
    }
    catch (Exception ex)
    {
    Log.Error(LOG_TAG, ex.Message.ToString());
    }
    //if (mBadge == null)
    //{
    // mBadge = new DefaultBadger(context);
    //}

    Log.Debug(LOG_TAG, "Returning badger: " + mBadge.ToString());

    return mBadge;
    }
    }

    ReplyDelete
  19. My services with error in this line: Badge badge = new Badge(this)
    [Service(Name = "com.teste.br")]
    public class NotificationService : IntentService
    {
    const string packagename = "com.teste.br";
    protected override void OnHandleIntent(Intent intent)
    {
    Android.Util.Log.Info("CHECK", "NotificationService");
    // The manufacturer of the product/hardware.
    int badgeno = intent.GetIntExtra("Countvalue", 0);
    Badge badge = new Badge(this);
    badge.count(badgeno);
    }

    }

    ReplyDelete
  20. Please, uncomment all lines commented and try out. See if you get an error.

    ReplyDelete
  21. Hi, Hetal, did you get it to download my project from Google Drive?

    ReplyDelete
  22. Replies
    1. Sorry for late reply

      I just got busy in something.

      I have updated the demo code and you can it and check what's missing in your application.

      https://drive.google.com/file/d/0B0dJLMU9SXZHZk4wTUp0N1N5NDQ/view?usp=sharing

      Delete
  23. Hetal, good morning. How can i do to reset a badge icon in my App? I commented the badge in MainActivity and after has generated the icon, my App ever show the icon. How can i do to hide or erase the icon? The badge is working, but i don't know how to reset. Lack knowledge for me.

    ReplyDelete
  24. Ok, i made a post, but when i was debugging i got it that load a cout to 0 that badge icon hide or disappear. I guess can get to make my App work with badge. Forget the post above

    ReplyDelete
  25. Hetal, good afternoon. How can i do to send message from my payload? Your plugin work fine, but i don't getting to send from my payload. I did a payload in wpf and i don't know how to send message. I'm trying but nothing.

    ReplyDelete
  26. Updated demo for Xamarin works for me.
    Thanks a lot.
    Tested on Samsung S5 and LG G3

    ReplyDelete
    Replies
    1. Can you share me the file which @hetal have provided

      Delete
  27. Hetal, good morning. I tried to do like you said me in forums.xamarin, but i still am not getting to update badge in background. What do i must to do?

    ReplyDelete
  28. Hello bro i cannot able to open the link which you have provided will you please share me another link.

    ReplyDelete