[Huawei Developers] Freemind R:
More information like this, you can visit HUAWEI Developer Forum

Original link:https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201327649924660033&fid=0101187876626530001

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/505/491/5190090000026505491.20200814052205.90826532152289974242898871574781:50510827012740:2800:5000814EE270F3F5558319CC910A70B5F94E2A060D814515B37CC1944D484210.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/505/491/5190090000026505491.20200814052205.90826532152289974242898871574781:50510827012740:2800:5000814EE270F3F5558319CC910A70B5F94E2A060D814515B37CC1944D484210.png[/IMG]​

If you have always wanted to make your own music player somewhere inside of you, this tutorial is for you. We will use Huawei’s relatively new AudioKit to develop one and I will show the steps one by one so that you can develop a music player on your own.

Do not rely on copy-pastes though, I am here to guide you, not let you copy-paste my code. To do that, you do not have to read this extensive tutorial, just click here to reach the full source code. Keep in mind that this source code contains three other HMS kits and their imperfect implementations, it is not a dedicated AudioKit-only app. However, if you are here to learn for real, let’s start below.

First of all, make sure you have everything you needed before starting to develop your app.

Hardware Requirements

A computer (desktop or laptop) running Windows 7 or Windows 10

A Huawei phone (with the USB cable), which is used for debugging

Software Requirements

Java JDK (JDK 1.7 is recommended.)

Android Studio 3.X

SDK Platform 19 or later

Gradle 4.6 or later

HMS Core (APK) 5.0.0.300 or later

Required Knowledge

Android app development basics

Android app development multithreading

Secondly, you should integrate Huawei HMS Core to your app. Details are listed here, in the official documentation. You should complete #3 and #4 until “Writing the Code” part. From now on, I will assume that you have prepared your application and ready to go with necessary devices attached for running.

Apart from this tutorial, you can always use sample app provided by Huawei, by clicking here. Source code gives idea about most concepts but it is not well-explained and the code is kind of confusing. My tutorial will also use that sample app but it will not be the same thing at all.

For app resources like play button, pause button, skip button etc., please find your own resources or use the resources provided by Huawei sample app that I provided the link above. If you already have resources available, you can use them too because it is very important to have a responsive UI to track music changes, but ultimately it does not matter how they actually look. From now on, I will also assume that you have necessary drawables/images/buttons for a standard music player. If you are going to use the app for commercial purposes, make sure the resources you use have no copyright issues.

End Product

If you want to know what kind of product we will be having in the end, look no further. The below screenshot roughly describes our end product after this relatively long tutorial. Of course, all customizations and UI elements (including colors) are up to you, so it could differ from my product.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/505/491/5190090000026505491.20200814051445.72316110501856563864431951514127:50510827012740:2800:EA4EDD915FA4DA645ED3D17F46C558D33A8AFC4AA59DB0A21F26B86FCEBC8DAA.jpeg"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/505/491/5190090000026505491.20200814051445.72316110501856563864431951514127:50510827012740:2800:EA4EDD915FA4DA645ED3D17F46C558D33A8AFC4AA59DB0A21F26B86FCEBC8DAA.jpeg[/IMG]

Also, as you can see my app contains AdsKit and Account Kit usages, which will not be included in this tutorial. That’s why, I will not give you the XML codes of my application (I already shared the my GitHub project link, if you are so inclined).

Remark: I mostly use the words audio file, music file and song(s) interchangably. Please do not get confused.

Let’s Plan!

Let’s plan together. We want to develop a music player application, so it should has some basic features that we want to support, such as play/pause, next/previous audio and seekbar updates. Seekbar will be showing us the progress of the music and it should be updated real time so that our music playback is always synced with life cycles of the app as well as the seekbar of our app. If you want to go further, we should add play modes, shuffle audio files, normal mode (sequential playback), loop the audio and loop the playlist. Of course, we want to render our cover image to the screen for a nice user experience and print the details of the audio file below it. And since we are only implementing the core features, we should have a playlist icon to open up the playlist and we should be able to choose an audio file from it. For the sake of simplicity, all browsed audio files from the device will be added to one single playlist for users to choose from. For the scope of this tutorial, creating new playlists, adding/removing files to those lists etc. are not supported. As can be predicted, our code will include a lot of button clicks.

I suggest you start with design on your own. Assuming that you have button/image resources you can imitate the design of my app (screenshot above) or your favorite music player. I placed the playlist button right above and clicking on it should open the playlist, and re-clicking should close it back. You can ignore the test ad below the playback buttons and AccountKit related parts above the cover image.

Let me remind you that I use view binding, so it is natural that you will not see much “findViewById”s. For official documentation of what I do, follow here.

Let’s code!

We should initialize our AudioKit managers to manage the playback later. Then, we should browse the local storage and get the audio files. After also completing listeners and notifications, we should implement button clicks so that users could have a smooth experience. Let’s start with a custom method called initializeManagerAndGetPlayList(…) to do the actual work, it is to be called in onCreate of the activity.

@SuppressLint("StaticFieldLeak")
public void initializeManagerAndGetPlayList(final Context context) {
new AsyncTask() {
@Override
protected Void doInBackground(Void... voids) {
HwAudioPlayerConfig hwAudioPlayerConfig = new HwAudioPlayerConfig(context);
HwAudioManagerFactory.createHwAudioManager(hwAudioPlayerConfig, new HwAudioConfigCallBack() {
@RequiresApi(api = Build.VERSION_CODES.R)
@Override
public void onSuccess(HwAudioManager hwAudioManager) {
try {
mHwAudioManager = hwAudioManager;
mHwAudioPlayerManager = hwAudioManager.getPlayerManager();
mHwAudioConfigManager = hwAudioManager.getConfigManager();
mHwAudioQueueManager = hwAudioManager.getQueueManager();
playList = getLocalPlayList(MainActivity.this);
if (playList.size() > 0) {
Collections.sort(playList, new Comparator() {
@Override
public int compare(final HwAudioPlayItem object1, final HwAudioPlayItem object2) {
return object1.getAudioTitle().compareTo(object2.getAudioTitle());
}
});
}
doListenersAndNotifications(MainActivity.this);
} catch (Exception e) {
Log.e("TAG", "player init fail", e);
}
}
@Override
public void onError(int errorCode) {
Log.e("TAG", "init err:" + errorCode);
}
});
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
PlaylistAdapter playlistAdapter = new PlaylistAdapter(playList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
binding.playlistRecyclerView.setLayoutManager(layoutManager);
playlistAdapter.setOnItemClickListener(MainActivity.this);
binding.playlistRecyclerView.setAdapter(playlistAdapter);
super.onPostExecute(aVoid);
}
}.execute();
}

Let me explain what we do here. We need a thread operation to create the managers and get the configuration in AudioKit. Thus, I used AsyncTask to do just that.

Remark: AsyncTask is currently deprecated so I would suggest you to use other methods if you care about modernity.

If AsyncTask succeeds, then I get my HwAudioManager instance and set it to my global variable. After that, using that manager instance, I get my player and queue managers. (and config manager as well but it will be used less frequently)

After getting my managers, I get my local playlist by a method I will share below. The collections code is just to sort the list alphabetically, you do not have to use it. Later, there is another method called doListenersAndNotifications(…), to set the notification bar and to attach the listeners, which is a crucial part in playback management.

In onPostExecute method, now that my managers are ready, I set my adapter for my playlist. However, we will get back to this later on. You do not need to worry about for now.

Let’s see how getLocalPlayList(…) works.

Beware: In order for below method to work, you must ask for the storage permission from the user explicitly. How to deal with it is your own responsibility. You must consider all cases (like user not giving consent etc.). The below method will work only after the storage permission is granted.

public List getLocalPlayList(Context context) {
List playItemList = new ArrayList<>();
Cursor cursor = null;
try {
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null) {
return playItemList;
}
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
selection,
null,
MediaStore.Audio.Media.TITLE);
HwAudioPlayItem songItem;
if (cursor != null) {
if(!cursor.moveToNext()){
//there is no music, do sth
return playItemList; //return empty list for now
}
else{
while(cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
if (new File(path).exists()) {
songItem = new HwAudioPlayItem();
songItem.setAudioTitle(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
songItem.setAudioId(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)) + "");
songItem.setFilePath(path);
songItem.setOnline(0);
songItem.setIsOnline(0);
songItem.setDuration(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)));
songItem.setSinger(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));
playItemList.add(songItem);
}
}
}
}
else{
Toast.makeText(this, "We have a serious cursor problem here!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("TAG,", "EXCEPTION", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
Log.i("LOCALITEMSIZE", "getLocalPlayList: " + playItemList.size());
return playItemList;
}

HwAudioPlayItem is the AudioKit’s POJO class for audio files. It contains the basic attributes of an audio file that developers can set, to use them later. Please note that, as of the publish time of this article, HwAudioPlayItem does not contain enough methods to initialize. Thus, some of the fields you consider you would use may be lacking. For example, there is no field for album name and thus my screenshot above always displays “Album Unknown”.

By this method, we browse the local music files, retrieve them in the format of HwAudioPlayItem and add them to a local list. Before returning, see the size of it in the logs. Our playlist is therefore ready, after this operation.

Now let’s see how I set listeners and implement notifications.

private List mTempListeners = new CopyOnWriteArrayList<>(); //a global variable
private void doListenersAndNotifications(final Context context) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
for (HwAudioStatusListener listener : mTempListeners) {
try {
mHwAudioManager.addPlayerStatusListener(listener);
} catch (RemoteException e) {
Log.e("TAG", "TAG", e);
}
}
mHwAudioConfigManager.setSaveQueue(true);
mHwAudioConfigManager.setNotificationFactory(new INotificationFactory() {
@Override
public Notification createNotification(NotificationConfig notificationConfig) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
builder = new NotificationCompat.Builder(getApplication(), null);
RemoteViews remoteViews = new RemoteViews(getApplication().getPackageName(), R.layout.notification_player);
builder.setContent(remoteViews);
builder.setSmallIcon(R.drawable.icon_notifaction_music);
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.setCustomBigContentView(remoteViews);
NotificationUtils.addChannel(getApplication(), NotificationUtils.NOTIFY_CHANNEL_ID_PLAY, builder);
boolean isQueueEmpty = mHwAudioManager.getQueueManager().isQueueEmpty();
Bitmap bitmap;
bitmap = notificationConfig.getBitmap();
setBitmap(remoteViews, bitmap);
boolean isPlaying = mHwAudioManager.getPlayerManager().isPlaying() && !isQueueEmpty;
remoteViews.setImageViewResource(R.id.image_toggle, isPlaying ? R.drawable.ic_notification_stop : R.drawable.ic_notification_play);
HwAudioPlayItem playItem = mHwAudioManager.getQueueManager().getCurrentPlayItem();
remoteViews.setTextViewText(R.id.text_song, playItem.getAudioTitle());
remoteViews.setTextViewText(R.id.text_artist, playItem.getSinger());
remoteViews.setImageViewResource(R.id.image_last, R.drawable.ic_notification_before);
remoteViews.setImageViewResource(R.id.image_next, R.drawable.ic_notification_next);
remoteViews.setOnClickPendingIntent(R.id.image_last, notificationConfig.getPrePendingIntent());
remoteViews.setOnClickPendingIntent(R.id.image_toggle, notificationConfig.getPlayPendingIntent());
remoteViews.setOnClickPendingIntent(R.id.image_next, notificationConfig.getNextPendingIntent());
remoteViews.setOnClickPendingIntent(R.id.image_close, getCancelPendingIntent());
remoteViews.setOnClickPendingIntent(R.id.layout_content, getMainIntent());
return builder.build();
}
else{
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplication(), null);
RemoteViews remoteViews = new RemoteViews(getApplication().getPackageName(), R.layout.statusbar);
builder.setContent(remoteViews);
builder.setSmallIcon(R.drawable.icon_notifaction_music);
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.setCustomBigContentView(remoteViews);
NotificationUtils.addChannel(getApplication(), NotificationUtils.NOTIFY_CHANNEL_ID_PLAY, builder);
boolean isQueueEmpty = mHwAudioManager.getQueueManager().isQueueEmpty();
Bitmap bitmap;
bitmap = notificationConfig.getBitmap();
setBitmap(remoteViews, bitmap);
boolean isPlaying = mHwAudioManager.getPlayerManager().isPlaying() && !isQueueEmpty;
remoteViews.setImageViewResource(R.id.widget_id_control_play,
isPlaying ? R.drawable.notify_btn_pause_selector : R.drawable.notify_btn_play_selector);
HwAudioPlayItem playItem = mHwAudioManager.getQueueManager().getCurrentPlayItem();
remoteViews.setTextViewText(R.id.trackname, playItem.getAudioTitle());
remoteViews.setTextViewText(R.id.artistalbum, playItem.getSinger());
remoteViews.setImageViewResource(R.id.widget_id_control_prev, R.drawable.notify_btn_close_selector);
remoteViews.setImageViewResource(R.id.widget_id_control_next, R.drawable.notify_btn_next_selector);
remoteViews.setOnClickPendingIntent(R.id.widget_id_control_prev, getCancelPendingIntent());
remoteViews.setOnClickPendingIntent(R.id.widget_id_control_play, notificationConfig.getPlayPendingIntent());
remoteViews.setOnClickPendingIntent(R.id.widget_id_control_next, notificationConfig.getNextPendingIntent());
remoteViews.setOnClickPendingIntent(R.id.statusbar_layout, getMainIntent());
return builder.build();
}
}
});
}
});
}
private void setBitmap(RemoteViews remoteViews, Bitmap bitmap) {
HwAudioPlayItem tmpItem = mHwAudioQueueManager.getCurrentPlayItem();
Bitmap imageCoverOfMusic = getBitmapOfCover(tmpItem);
if(imageCoverOfMusic != null){
Log.i("TAG", "Notification bitmap not empty");
remoteViews.setImageViewBitmap(R.id.image_cover, imageCoverOfMusic);
}
else{
if (bitmap != null) {
Log.i("TAG", "Notification bitmap not empty");
remoteViews.setImageViewBitmap(R.id.image_cover, bitmap);
} else {
Log.w("TAG", "Notification bitmap is null");
remoteViews.setImageViewResource(R.id.image_cover, R.drawable.icon_notifaction_default);
}
}
}
private Bitmap getAlbumImage(String path) {
try{
android.media.MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(path);
byte[] data = mmr.getEmbeddedPicture();
if (data != null)
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public Bitmap getBitmapOfCover(HwAudioPlayItem currItem){
if(currItem != null) {
String currentSongPath = currItem.getFilePath();
if (currentSongPath != null) {
Bitmap tmpMap = getAlbumImage(currentSongPath);
binding.albumPictureImageView.setImageBitmap(tmpMap);
return tmpMap;
}
}
return null;
}
private PendingIntent getCancelPendingIntent() {
Log.i("TAG", "getCancelPendingIntent");
Intent closeIntent = new Intent("com.menes.audiokittryoutapp.cancel_notification");
closeIntent.setPackage(getApplication().getPackageName());
return PendingIntent.getBroadcast(getApplication(), 2, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent getMainIntent() {
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setClass(getApplication().getBaseContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
return PendingIntent.getActivity(getApplication(), 0, intent, 0);
}

Let me explain here. I know it looks complicated but most of it is almost copy-paste boiler plate code. First we attach listeners in a looper, HwAudioStatusListener is AudioKit’s listener class. After that we save our queue and set the notification bar. I use this code with else part almost commented out due to support issues but you may copy and paste it to try it out in lower versions of Android. That being said, it should be clear that you should update the resource names as per your needs/wants.

setBitmap(…) method is to render the cover image in notification bar layout. (You can find the customized layout in GitHub link I shared). You cannot find this method in this way in sample apps. It is a cool and important feature, so I suggest you use it. Also, there is a NotificationUtils class for additional notification bar related codes, and you may also find it in the GitHub. You do not have to put them separately, you can copy those code to MainActivity and still use them, if you think that that will not be overcomplicating your code.

Also the other Bitmap methods will let you use the setBitmap(…) method correctly. Also, they will be useful when rendering the cover image to main screen too. Since HwAudioPlayItem class do not have a field for image paths for easy renders, I had to use more than 2 methods to use the path of the song to retrieve the cover image and then use it to get the Bitmap of it.

Other intent methods are to implement the feature of close button to cancel the notification and for the main intent.

The End for now!

The rest of the application will be talked about in Part 2 of this series. We will be implementing onCreate method, button clicks and listeners in detail. See you there.