https://dzone.com/articles/notification-channels-in-android-oreo


Android devs should be aware that their apps will stop sending notifications to users if they target API 26 - learn to avoid this by implementing notification channels.

In (not-so) recent news, Google is going to enforce that all apps target SDK 26 (Android Oreo) by late 2018, in order to ensure security and improved performance in apps. You can read more about the announcement here.

Now, it’s pretty easy to target API 26, but there’s no guarantee that your app will function as it used to by just changing the targetSdkVersion value in your build.gradlefile.

This post looks specifically at one of the new things introduced in Android Oreo, and how targeting API 26 will affect your app, and notifications - notification channels (or categories).

TL;DR

Your app will stop sending notifications to the users if you target API 26 and you don’t implement notification channels.

What Are Notification Channels?

In Android O, notification channels are somewhat like groups or categories of notifications - say you’re building a social networking app, the channels can be “activity” - likes, or comments on your posts, “messages,” etc. In fact, in the settings of your app, the user sees channels as “categories” as seen in the screenshot below.

Notification Settings screenshot showing different notification categories

With the introduction of notification channels, users can get a fine control of what they want to be notified about. They can specifically turn off notifications for a certain channel, specify the importance as well as the preferred sound for a particular category of notifications and determine whether or not to override DND (Do not disturb)

Implementing Notification Channels

Creating Notification Channels

These notification channels are created at runtime, so they can be dynamically changed to fit the requirements of your the user. For example, if a user subscribes to group chat, for example, you can create a channel matching that particular group, and when they leave the group, you can remove the notification channel.

So how then does one add channels to notifications? At the simplest level, one needs to create a channel with a unique name and ID and a level of importance. The uniqueness of the name and ID only refers to your app package. The notification manager then does the creation of the channel with whatever settings you specify. Typically the creation code looks like:

val privateMessagesChannel = NotificationChannel(
                    PRIVATE_MESSAGES_CHANNEL_ID,
                    context.getString(R.string.pm_channel_name),
                    NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(privateMessagesChannel)


It’s worthy of note that you can also create channel groups. This is useful in scenarios where you have multiple accounts or profiles so you can group the notification channels per account/profile.

You can specify further customizations for the channel you have created. For example, you can specify the light colors, vibration pattern etc. for the channel as shown below:

with(privateMessagesChannel) {
    lightColor = Color.RED
    enableVibration(true)
    vibrationPattern = longArrayOf(100, 200, 300, 400)
}


Sending Notifications for a Notification Channel

Now that we’ve created the channel, next step is to actually specify the channel whenever we want to show a notification and that is done when creating a new notification. Specifying a channel for the notification looks like:

val notification = NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_notification_small)
                .setContentTitle(context.getString(R.string.notif_pm_title))
                .setContentText(message)
                /**
                 * further notification customizations
                 */
                .setChannelId(PRIVATE_MESSAGES_CHANNEL_ID)
                .build()
        notificationManager.notify(PM_NOTIFICATION_ID, notification)


The part of the code above that sets the channel is .setChannelId(). Without this line, if you’re targeting Android O and above, your notification will not be shown to the user.

Updating/Reading Notification Channels Settings

After creating notification channels, the ability to control is left to the user. They can turn off notifications, change priority, lights and vibration settings etc. for any channel they desire. However, it is possible to programmatically read the current channel settings. You may need this so that you can present the status of the notification channel to your user. For example, if the user has turned off notifications for a certain group chat, you may display a “mute” icon next to the group details or somewhere it’s visible to the user.

It’s important not to make this intrusive in any way or obstruct users from going about their normal activities in the app because it defeats the purpose of giving users the power to control the settings for the channel.

To read the notification channel details, you need to get a reference to the notification channel, and query the settings you desire.

val pmNotificationChannel = notificationManager.getNotificationChannel(PRIVATE_MESSAGES_CHANNEL_ID)
val channelIsBlocked = pmNotificationChannel.importance == NotificationManager.IMPORTANCE_NONE
if (channelIsBlocked) {
// do something unintrusive to make user aware that they blocked the notification
// you should also provide a way to make them go to the channel settings
}


The code block above shows how we can check for the importance setting for the channel, we can do similar for lights, vibration, and other settings

To provide a well-rounded experience, it is advisable to help users access the notification settings where they can update their notifications. You can place this somewhere in your settings menu. There is an intent available for the notification settings, and constructing code looks like:

val notificationSettingsIntent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
notificationSettingsIntent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
startActivity(notificationSettingsIntent)


Deleting Notification Channels

So let’s assume that a user has unsubscribed from a previous conversation that a channel was created for. You will have to delete the channel. Deleting is quite straightforward. To do this, one needs to do something like:

notificationManager.deleteNotificationChannel(PRIVATE_MESSAGES_CHANNEL_ID)


Extra

There are some additional thoughts & questions that come up regarding notification channels. Some of them include

  • When is the best time to set up notification channels? On app start? When is the user profile ready? Just before showing the notification? Dan Lew has some thoughts about this.
  • What if I really really need to show the notification to the user? - We have this covered in this post. The final decision about notification settings is up to the user, once the channels have been created and a notification posted to the channel. If the user modifies the setting to one that doesn’t make them fully enjoy the app, you can unobtrusively make them aware of this - using a dismissable card or something of that nature. I personally won’t advice using an alert or complete breakdown of the app.
  • What about pre-O devices? If you support devices below API level 26, you will probably get a lot of lint warnings as you implement this. NotificationManagerCompat doesn’t (yet) contain methods to create, update & delete the channels. This suggests that you may need to have a NotificationManager to handle these things for API level 26+. Also related to this, the NotificationCompat.Builder already adds support for setting channel ids to which notifications will be posted, so you can still use NotificationCompat.Builder to build your notifications (for backward compatibility)

Further Reading

Here are some resources that may come in handy for further reading on notification channels:

Summary

In conclusion, the new notification channels in Android provide an improved experience for users - in terms of gaining more control over notifications, and this also helps us developers to be more decent in our use of notifications. At the end of the day, it’s a win-win situation.

Finally, remember that come August 2018 for new apps and November for app updates, you will be required to target Android O (API level 26) or higher. And as a result, this will require you to implement notification channels if you show notifications in your app.

If you want to see some more code, I have a demo project with some of these implementations available on GitHub, check it out here.

Thanks to Moyin for helping to review this post.

Thanks for reading this post. Please feel free to give feedback, suggestions, corrections etc. Also, if you found the post useful, please share and/or leave a comment.

Topics:
 
MOBILE ,NOTIFICATIONS ,ANDROID ,ANDROID OREO ,TUTORIAL ,MOBILE APP DEVELOPMENT
 

 Comment (0)

 
Save
 
 8,421 Views

Published at DZone with permission of 

Opinions expressed by DZone contributors are their own.

What Is the EventBus Library and How Does It Work?

Learn about the EventBus library for Android and how it makes it easier to manage communication between components in your application.

  · Mobile Zone · Tutorial
 

 Comment (5)

 
Save
 
 266.5k Views

EventBus is an open-source Android library that simplifies communication between Activities, Fragments, Threads, and Services, with less code and better quality. When we develop an Android application, we need to manage a lot of intercommunication between Android components, which sometimes becomes very difficult to manage. The EventBus library makes this task easy.

Why EventBus?

The main reason we should use EventBus is loose coupling. Sometimes, you want to process specific events that are interested in multiple parts of your application, like the presentation layer, business layer, and data layer, so EventBus provides an easy solution
for this.

Features of the EventBus Library

  1. Simple, yet powerful.

  2. Battle-tested.

  3. High performance.

  4. Convenient annotation-based API.

  5. Event and subscriber inheritance.

You need to have four things to implement EventBus:


1. An EventBus object.

EventBus myEventBus = EventBus.getDefault();

2. An Event normal POJO class.

public class DataSyncEvent {
    private final String syncStatusMessage;
    public DataSyncEvent(String syncStatusMessage) {
        this.syncStatusMessage = syncStatusMessage;
    }
    public String getSyncStatusMessage() {
        return syncStatusMessage;
    }
}

3. The sender which will send the event.

EventBus.getDefault().post(new DataSyncEvent("Sync SuccessFully”);

4. The subscriber, someone who will listen to our event.

@Subscribe
public void onEvent(DataSyncEvent syncStatusMessage)
{
    Toast.makeText(this, syncStatusMessage.getSyncStatusMessage(), Toast.LENGTH_SHORT).show();
}

The last two steps are to register and unregister the EventBus that wants to listen to the event. The best way is to register it in the onStart method and unregister it in the onStop method of the activity.

@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

Let's take a simple example. In our project, if we want to sync our data to the server at the time of the application's launch, for this, simply start an intent service from the launcher activity of your application and, through the intent service, sync the data to the server. After that, notify the screen (through theEventBus library) which is currently visible to the user about syncing.

Implementation of EventBus

Add the dependencies in the gradle file.

compile 'de.greenrobot:eventbus:2.4.0'

Add the intent service class, which will start at the time of application launch.

    public class SyncDataService extends IntentService
    {
        public SyncDataService()
        {
            super("SyncDataService");
        }
        @Override
        protected void onHandleIntent(Intent intent)
        {
            //first check if internet is availabe or not.
            if(DeviceManager.isInternetAvailableOnDevice())
            {
//            try
//            {
//              //write the code to sync the data to Server
                //post the event after sync complete 
                EventBus.getDefault().post(new DataSyncEvent("Data Sync SuccessFully"));
//            }
//            catch (RTITBException exception)
//            {
//                LogManager.getInstance().addLog(exception.getExceptionCode(),exception.getMessage(),exception);
//            }
            }
        }
    }

The main Activity:

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //Register the EventBus
    @Override
    protected void onStart()
    {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    //UnRegister the EventBus
    @Override
    protected void onStop()
    {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    //The Method which will call every time when data sync to server
    @Subscribe
    public void onEvent(DataSyncEvent syncStatusMessage)
    {
        //you can do whatever you want releted with UI
        Toast.makeText(this, syncStatusMessage.getMessage(), Toast.LENGTH_SHORT).show(); 
    }
}

If any other component of your application wants to listen to the event, we only need to register for the EventBus as mentioned in the above method onStart and override the method onEvent.

The EventBus library is just like a radio frequencyl; if you wish to listen to any song, you simply need to set the frequency to that station. Likewise, the EventBus library posts events; if any component wants to listen to that event, then we need to register that component for the EventBus object and we will get that event in the onEvent method.

Topics:
 
EVENTBUS,EVENT LISTENERS,MOBILE,MOBILE APP DEVELOPMENT,TUTORIAL,ANDROID
 

 Comment (5)

 
Save
 
 266.5k Views

Published at DZone with permission of Abhishek Tripathi . See the original article here.

Opinions expressed by DZone contributors are their own.

Secrets Behind the Most Successful App Launches

When developing a mobile app, make sure your idea is in demand, and follow these tips from the most successful app launches like Instagram and Snapchat.

  · Mobile Zone · Opinion
 

 Comment (8)

 
Save
 
 73.94k Views

Some people think that success comes from hard work. Others think it comes from luck. When it comes to creating a successful app that will drive good app revenue, you need something more than hard work and luck. You need an edge which makes your startup app stand out from all the other ones on the market. The first thing you need to worry about is developing an application which has demand and can be useful to people. This is one of the main success factors app needs to take off. You will know if you have accomplished this after you launch a beta version and allow people to test it out. Based on their feedback from using your app, you will know what works and what doesn’t. But even that is not enough for your app to skyrocket most of the time. Read below about most successful app launches to find out what helped the most popular mobile applications get to almost every smartphone on Earth.

Instagram: Invited Influencers

Kevin Systrom, who is the founder of Instagram, has one of the most successful app launches. He allowed the company’s Minimum Viable Product to be reviewed by technology influencers in the industry. One such influencer included Twitter’s co-founder Jack Dorsey. As soon as Dorsey started using the app, he was already sending pictures to his followers on Twitter. It didn’t take long for the word-of-mouth to spread about the app. TechCrunch also featured two articles about the app, one prior to the app’s official launch date and another on the same day when the app was launched. Needless to say, his provided even more word-of-mouth traffic for the app. 

Within 24 hours of the launch, there were 25,000 users on Instagram. By week 3, there were 300,000 Instagram users. This number just kept growing until there were tens of millions of users. Important move that made Instagram release one of the most successful app launches was doing it immediately after the iPhone 4 release date. Since the iPhone 4 featured an enhanced camera and screen, this became the perfect combination for to make Instagram a popular app. Another thing that helped Instagram was how they made their app capable of sending pictures to popular social media platforms like Twitter and Facebook. This meant the pictures weren’t locked into the app. The speed of the app is really important for app users. That’s why for the Instagram wanted to speed up uploading of the pictures. So they made the pictures start uploading immediately after they are taken. The size of the pictures was kept small too.

Snapchat: Created Excitement in Their Target Audience

Snapchat release definitely holds a place at “the most successful app launches” chart. The original founders of Snapchat first drew attention to their app at Stanford University. They told some of their college buddies there about the app which got it some attention. However, it didn’t gain national popularity until high schoolers started discovering the app. Very fast this startup app became super popular messaging app amongst teenagers.

There was someone who attributed the steady growth of Snapchat to the group messaging feature that it has. Instead of just sending an individual message to someone, a user can send something called a “snap” to several people at once. It is basically like sending messages to a group of people at once. The only difference is that snaps create a personal feeling in the recipients which you cannot achieve through regular mass messaging. This one is a big success factor app has.

Most Snapchat users feel comfortable sending snaps because as soon as the recipients open them, they will vanish within a few seconds. This means all their personal messages will not get saved to some history log on the Internet.

Evernote: Attracted Attention From the Press

What makes the release of Evernote one of the most successful app launches? When Phil Libin was interviewed about the growth of Evernote, he credited the original press coverage of its closed beta app as the reason. Evernote went on to having millions of users within a couple of years. The closed beta was what ultimately led to this growth. After just a couple of days from its initial press coverage, thousands of people signed up for Evernote’s closed beta. Not only that, the first groups of users told their friends and family about it too. This gave the closed beta a lot of word-of-mouth traffic.

Evernote developed a marketing strategy during its first few years which involved having an app available for every platform and device on the market. In other words, if a new tablet or mobile phone came out, Evernote would have an app already available which was compatible with it right from the beginning. This made it easier for Evernote to dominate their competition and get their apps seen by virtually all mobile users.

Clear: Kept It Simple and Unique

The Clear app was designed very uniquely when it was first conceived. This “to-do list” app contains no buttons because it was designed to be simple to use. Compare this with other to-do-list apps which have lots of buttons and other complicated functions that are difficult to figure out. Since the Clear app was easy to figure out and use, people quickly began to love it. That way, people that want to make a simple to-do list on their mobile device can do so without the hassle.

The Clear app’s founders had a marketing strategy which involved getting coverage from technology blogs. They would release teaser videos and previews of their app prior to it being released. Then, after the app did launch, about 350,000 copies of it were sold in just 9 days. Certain members of the press were invited to try out the beta version of the app and then give their feedback on it.

Clear was first introduced in January of 2012 at the MacWorld event. The founders uploaded a video demo of the app onto Vimeo and it was viewed over 814,000 times. This helped create a lot of gossip and interest in the app prior to its February 2012 launch date.

Camera+: Used Social Media Aggressively

The last app in our “the most successful app launches” list. The Camera+ app’s founders announced their release through popular social media platforms. These are social media platforms which are compatible with the app. For example, if a user took a picture with Camera+, they could email the picture or share it on Twitter, Flickr, or Facebook. At the time, no other app had a sharing feature like this one. On top of that, the founders promoted the launch by offering a contest which was giving away camera equipment valued at over $10,000. They were also able to spread the message about the launch on their mailing list which already had close to 70,000 subscribers on it.

Another strategy that the founders used was not focusing on domestic sales only. They understood that numerous other countries around the world did not have an app as good as theirs. So, they released it to international markets and got a fast response in the Apple Store. It even became the App of the Week in the Apple Store at one point.

One of the co-founders ran a blog and posted a video there which showed the newest update in version 1.2 of the app. This immediately created more enthusiasm for the app as users anxiously awaited the update, so they could have the newest feature.