how to Provide intent for cards - Android Q&A, Help & Troubleshooting

How to give intent for accessing card activity,its not taking usual class.
Below is code snippet im providing. can anyone provide me solution
actually im developing simple app for kitkat android mobile.this app is just to access list thats why im using cards.
public void onClick(View v) {
if(txtUsername.getText().toString().equals("test") &&
txtPassword.getText().toString().equals("1234")){
Toast.makeText(getApplicationContext(), "Credentials Accepted",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login_activity.this, HelloCardActivity.class); //hellocardactivity is another card activity. and login_activity is login page
startActivity(i);
Login_activity.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
}
}
pls provide a solution
thank you

Related

[Q] Android Java/Development - WebView findall function

Hello all,
Frankly I am not sure that this even belongs here but I think its the closest fit to the forum that I am seeking. If there is a community better suited to answer this please direct me there I have a question about the findall function in webviews. I know that it is deprecated, in eclipse this comes up "The method findAll(String) from the type WebView is deprecated". This is the code I have:
Code:
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& ((keyCode == KeyEvent.KEYCODE_ENTER))) {
wv.findAll(findBox.getText().toString());
try {
Method m = WebView.class.getMethod("setFindIsUp",
Boolean.TYPE);
m.invoke(wv, true);
} catch (Exception ignored) {
}
}
return false;
}
I just want to have a functioning find/search in a webview. So far this functions great for only some versions of android, versions such as 4.0, 4.0.3, and I believe 3.0 do not function correctly.
Older versions of android such as the 2.x series and my nexus s on 4.1 work great.
Anyone know of a workaround for a webview function to work on all android versions? If there is something completely different form this I am willing to listen, at this point I only am looking for a functioning search on all versions.
Thanks everybody!

[Q] Xposed developing for 5.1 cm12.1

Hello
My phone is the moto x 2014 running CM12.1 nightly.
i was trying to learn how to develop modules for my rom using this tut.
Everything was fine using this code
Code:
package de.robv.android.xposed.mods.tutorial;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class Tutorial implements IXposedHookLoadPackage {
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("com.android.systemui"))
return;
});
}
}
but when i add the hook method
Code:
findAndHookMethod("com.android.systemui.statusbar.policy.Clock", lpparam.classLoader, "updateClock", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// this will be called before the clock was updated by the original method
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// this will be called after the clock was updated by the original method
}
System UI crashes on startup and i need to reboot to recovery and disable xposed.
The Question​what is going wrong? is this tutorial outdated for 5.1 am i missing something?
logs are in attachement, for more info plz don't hesitate to ask.
Use latest build
http://forum.xda-developers.com/xposed/super-alpha-posted-permission-xposed-t3072979
For me it doesn't work.
I flashed the zip with twrp, the phone rebooted successfully but I can't find the xposed program from the app menu. Maybe I missed something?
I am on g3 with 5.1.1 cyanidel.
Thanks!
half cooked
Stefano Bottari said:
For me it doesn't work.
I flashed the zip with twrp, the phone rebooted successfully but I can't find the xposed program from the app menu. Maybe I missed something?
I am on g3 with 5.1.1 cyanidel.
Thanks!
Click to expand...
Click to collapse
Your food is half cooked....
After flashing it through twrp you have to install xposed 3.0 alpha apk .

How Do I Get ContentResolver Query To Check if Events Exists In The Calendar Or Not?

I need help with this code that I've been trying to figure out for hours. I know it's something close to what I have from my research, but I can't get it to work. Not even the codes provided from other posts on other sites. Any ideas?
public void checkEventsInCal() {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/events"), new String[]{"_id"}, "_id=?", new String[]{CalendarContract.Events.TITLE}, null);
if (cursor.moveToFirst()) {
Toast.makeText(this,"Event Exists!", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Event Doesn't Exist!", Toast.LENGTH_SHORT).show();
}
}
Thanks in advance for your help!!
Can I get a working solution please. Someone please respond. Thanks!

How to make your own music player using HMS Audio Kit: Extensive Tutorial Part 1

More information like this, you can visit HUAWEI Developer Forum
Original link:https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201327649924660033&fid=0101187876626530001
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
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.
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.
Code:
@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.
Code:
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.
Code:
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.

Track the performance for In-App links using HUAWEI APP LINKING

Introduction
In-App linking is refer to App linking or deep linking in general, however it is particularly for the use case of sharing content with the same application for the same application installed on the android device.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Huawei App Linking leverage developers/users to create cross platform links which can work as defined and can be distributed with multiple channels to users.
When the user clicks the link, it will be re-directed to the specified in-app content.
Huawei App Linking has multiple functions:
1. Support for deferred deep links
2. Link display in card form
3. Data statistics
Huawei App Linking supports the link creation in multiple ways:
1. Creating a link in AppGallery Connect
2. Creating a link by calling APIs on the client
3. Manually constructing a link
Creating a link in AppGallery Connect
We will be focusing on the Huawei App linking capabilities to create the deep links for our Android application through Huawei AppGallery Connect.
Use Case
There could be multiple use cases for this capability, however I will throw some light on a use case which is most commonly adapted by the applications with complex UX and high transmission between different in-app pages.
Development Overview
1. Must have a Huawei Developer Account
2. Must have Android Studio 3.0 or later
3. Must have a Huawei phone with HMS Core 4.0.2.300 or later
4. EMUI 3.0 or later
Software Requirements
1. Java SDK 1.7 or later
2. Android 5.0 or later
Preparation
1. Create an app or project in Android Studio.
2. Create an app and project in the Huawei AppGallery Connect.
3. Provide the SHA Key and App Package name of the project for which you want the App Linking to be done (Example: News application)
4. Download the agconnect-services.json file and paste to the app folder of your android studio.
Integration
Add below to build.gradle (project)file, under buildscript/repositories and allprojects/repositories.
Java:
Maven {url 'http://developer.huawei.com/repo/'}
Add below to build.gradle (app) file, under dependencies to use the App Linking SDK.
Java:
dependencies{
// Import the SDK.
implementation 'com.huawei.agconnect:agconnect-applinking:1.4.1.300'
}
News Application
News application is developed with multiple content and complex UX to show the capability of the Huawei App Linking.
I will highlight some if the important code blocks for this application.
Main Activity
This activity is the entry point for the application which will have the navigation tab to handle the multiple news categories.
Also, it receives the App Link, read it and re-direct it to the corresponding content.
Java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ViewPager viewPager;
FloatingActionButton AddLinks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Find the view pager that will allow the user to swipe between fragments
viewPager = findViewById(R.id.viewpager);
// Give the TabLayout the ViewPager
TabLayout tabLayout = findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
// Set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
NavigationView navigationView = findViewById(R.id.nav_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
// Set the default fragment when starting the app onNavigationItemSelected(navigationView.getMenu().getItem(0).setChecked(true));
// Set category fragment pager adapter
CategoryFragmentPagerAdapter pagerAdapter =
new CategoryFragmentPagerAdapter(this, getSupportFragmentManager());
// Set the pager adapter onto the view pager
viewPager.setAdapter(pagerAdapter);
AddLinks.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
shareLink("https://bulletin.dra.agconnect.link/yAvD")
}
});
//Receive and re-direct app link
recievelink();
}
//Receive applinks here
private void recievelink()
{ AGConnectAppLinking.getInstance().getAppLinking(getIntent()).addOnSuccessListener(new OnSuccessListener<ResolvedLinkData>() {
@Override
public void onSuccess(ResolvedLinkData resolvedLinkData) {
Uri deepLink1 = null;
if (resolvedLinkData != null) {
deepLink1 = resolvedLinkData.getDeepLink();
String myLink= deepLink1.toString();
if(myLink.contains("science")) {
viewPager.setCurrentItem(Constants.SCIENCE);
}
try {
Toast.makeText(MainActivity.this, deepLink1.toString(), Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e("LOG ", "Exception Occured : " + e.getMessage());
e.printStackTrace();
ApiException apiException = (ApiException) e;
Log.e("LOG ", "status code " + apiException.getStatusCode());
}
});
}
private void shareLink(String appLinking) {
if (appLinking != null) {
System.out.println("inside button click " + appLinking);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, appLinking);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
// Switch Fragments in a ViewPager on clicking items in Navigation Drawer
if (id == R.id.nav_home) {
viewPager.setCurrentItem(Constants.HOME);
} else if (id == R.id.nav_world) {
viewPager.setCurrentItem(Constants.WORLD);
} else if (id == R.id.nav_science) {
viewPager.setCurrentItem(Constants.SCIENCE);
} else if (id == R.id.nav_sport) {
viewPager.setCurrentItem(Constants.SPORT);
} else if (id == R.id.nav_environment) {
viewPager.setCurrentItem(Constants.ENVIRONMENT);
} else if (id == R.id.nav_society) {
viewPager.setCurrentItem(Constants.SOCIETY);
} else if (id == R.id.nav_fashion) {
viewPager.setCurrentItem(Constants.FASHION);
} else if (id == R.id.nav_business) {
viewPager.setCurrentItem(Constants.BUSINESS);
} else if (id == R.id.nav_culture) {
viewPager.setCurrentItem(Constants.CULTURE);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
// Initialize the contents of the Activity's options menu
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the Options Menu we specified in XML
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
// This method is called whenever an item in the options menu is selected.
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Creating a link in AppGallery Connect to directly open the Science tab for the News Application through a link
1. Login to AppGallery Connect.
2. Choose My Projects > NewsWorld(App Linking).
3. Go to>Growing > App Linking>Enable now
4. Once you enable the app linking for your project by setting up the country and region choose URL prefix>Add URL prefix
Add URL prefix, which is a free domain name provided by AppGallery Connect with a string.
Tip: URL prefix should be unique and can contain only lowercase letters and digits.
Select Set domain name option and then click on Next button.
The following page will be displayed.
6. Click App Linking and then click Create App Linking for deep linking purpose. It is required to directly navigate to specific in-app content from a different application.
7. It will suggest short link by itself or you can customise it as shown below.
8. Click on Next button and set the deep link.
App Linking name: deep link name.
Default deep link: deep link used to open an app.
Android deep link: deep link preferentially opened on an Android device.
iOS deep Link URL: deep link preferentially opened on an iOS device.
Tip 1: Link name and Default deep link can be same and follow as https://domainname.com/xxx
Where “domainname” is URLprefix which we set above and “xxx” is specific in-app content page to re-direct.
Tip 2: You can customize the deep link, which is different from the URL prefix of the link.
Once done, click on Next button.
9. Select Set Android link behaviour for your Android application as below.
We will choose “Open in app” as we want our application to open directly as application.
Select your application from the Add Android app menu.
Redirect user to AppGallery page if the application is not installed on the device.
Tip: Ensure that the App Store ID and team ID have been configured. If they are not configured, add them as prompted.
Once done, click on Next button.
10. We have set the deep link for our news application and it will re-direct to in-app content tab (science) every time when it is shared from our share application.
To check the details and use the link we will navigate to view details
11. We will use short App link for our App Linking use case. It will re-direct the user to Science tab of news application from our shared link through different tab.
Receiving Links of App Linking
When a user is directed to the target content after tapping a received link of App Linking, your app can call the API provided by the App Linking SDK to receive the tapped link and obtain data passed through the link.
Add an Intent Filter to manifest file
Add intent filter to activity which will receive and process the link.
We will add this for Main activity for our use case.
Java:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="yourdomainname.com"
android:scheme="https"
tools:ignore="AppLinkUrlError" />
</intent-filter>
Receive the link in our Main activity
Add below code to your activity to receive and process the link.
Java:
AGConnectAppLinking.getInstance().getAppLinking(getIntent()).addOnSuccessListener(new OnSuccessListener<ResolvedLinkData>() {
@Override
public void onSuccess(ResolvedLinkData resolvedLinkData) {
System.out.println("inside button click_rcv " + resolvedLinkData.getDeepLink());
Uri deepLink1 = null;
if (resolvedLinkData != null) {
deepLink1 = resolvedLinkData.getDeepLink();
String myLink= deepLink1.toString();
if(myLink.contains("science")) {
viewPager.setCurrentItem(Constants.SCIENCE);
}
try {
Toast.makeText(MainActivity.this, deepLink1.toString(), Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e("LOG", "Exception Occured : " + e.getMessage());
e.printStackTrace();
ApiException apiException = (ApiException) e;
Log.e("LOG ", "status code " + apiException.getStatusCode());
}
});
Check Statistics for your links
Huawei App Linking provides lot many additional features to track the statistic for the created in-app links for your application which will be helpful in order to generate the analytical reports and improve the performance.
Step 1: Click on Statistics
Step 2: Check the performance graph based on the filters
Results
Tips and Tricks
1. URL prefix should be unique and can contain only lowercase letters and digits.
2. Link name and Default deep link can be same and follow as https://domainname.com/xxx
Where “domainname” is URLprefix which we set above and “xxx” is specific in-app content page to re-direct.
3. You can customize the deep link, which is different from the URL prefix of the link.
4. Ensure that the App Store ID and team ID have been configured. If they are not configured, add them as prompted.
Conclusion
This article focuses explains how in-app links can be created using Huawei App Linking capabilities and use them further for in –app content re-directions for large scale android applications. This article also explains how one can check the statistics for their app links.
Reference
https://developer.huawei.com/consum...ry-connect-Guides/agc-applinking-introduction

Categories

Resources