Add query parameters to link in firebase dynamic link - android

I create dynamic link and I want to send some specific parameter, like:
"https://mydynamiclink/?link=" + link + "&msgid=" + id + "&apn=myapn".
link field looks like "https://play.google.com/store/apps/details/?id=com.myApp&msgid=myId&apn=myapn"
When I open my app after taping on this link - I receive PendingDynamicLinkData and can get link from it, but not some custom data. (pendingDynamicLinkData.getLink() returns my link without "&msgid=..." - I'm getting string "https://play.google.com/store/apps/details/?id=com.myApp")
How can I add my msgid field and get it after all?

I've found solution
String query = "";
try {
query = URLEncoder.encode(String.format("&%1s=%2s", "msgid", id), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final String link = "https://play.google.com/store/apps/details/?id=com.myApp" + query;
After such encoding pendingDynamicLinkData.getLink() returns me https://play.google.com/store/apps/details/?id=com.myApp&msgid=myId

Accepted answer didn't work out fine for me, all i needed to do was check if the link was for a user's profile and not a blog post, so i can redirect to my ProfileActivity instead.
private void generateDynamicLink() {
//build link normally and add queries like a normal href link would
String permLink = getLink() + "?route=profile&name=" + getProfileName()
+ "&category=" + getUserPracticeCategory()
+ "&picture=" + getProfilePicture();
FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse(permLink))
.setDynamicLinkDomain(Constants.DYNAMIC_LINK_DOMAIN)
.setAndroidParameters(new
DynamicLink.AndroidParameters.Builder().build())
.setSocialMetaTagParameters(
new DynamicLink.SocialMetaTagParameters.Builder()
.setTitle("Enter Title")
.setDescription("Enter Desc here")
.setImageUrl(Uri.parse(getProfilePicture()))
.build())
.buildShortDynamicLink()
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,task.getResult().getShortLink());
intent.setType("text/plain");
startActivity(intent);
} else {
Utils.snackBar(tvAddress, "Failed to Generate Profile Link, Try
Again");
}
});
}
and when a user navigates into my app using the generated link, it goes to a post detail activity, because i made that activity the only browsable activity in my manifest. i then have to use the route query to determine if the incoming link is a blog post or a shared user profile.
private void retrieveDynamicLink() {
FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
.addOnSuccessListener(this, pendingDynamicLinkData -> {
if (pendingDynamicLinkData == null) {
retrieveLocalIntent();
} else {
Toast.makeText(context, "Resolving Link, Please Wait...", Toast.LENGTH_LONG).show();
if (pendingDynamicLinkData.getLink().getQueryParameter("route") != null) {
if (Objects.requireNonNull(pendingDynamicLinkData.getLink().getQueryParameter("route")).equalsIgnoreCase("profile")) {
try {
Uri uri = pendingDynamicLinkData.getLink();
String permLink = uri.toString().split("\\?")[0];
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra(ProfileActivity.PROFILE_NAME, uri.getQueryParameter("name"));
intent.putExtra(ProfileActivity.PROFILE_CATEGORY, uri.getQueryParameter("category"));
intent.putExtra(ProfileActivity.PROFILE_PICTURE, uri.getQueryParameter("picture"));
intent.putExtra(Utils.POST_PERMLINK, permLink);
startActivity(intent);
this.finish();
} catch (NullPointerException e) {
Toast.makeText(context, "Unable to View User Profile", Toast.LENGTH_SHORT).show();
}
}
} else {
postHrefLink = pendingDynamicLinkData.getLink().toString();
getPostDetail.getData(postHrefLink);
}
}
})
.addOnFailureListener(this, e ->
retrieveLocalIntent()
);
}
Hope this helps.

1 First Change your Dynamic Link in firebase console from http://exampleandroid/test to http://exampleandroid/test?data
2. You send the query paramter data with this
DynamicLink dynamicLink = FirebaseDynamicLinks.getInstance().createDynamicLink()
// .setLink(dynamicLinkUri)
.setLink(Uri.parse("http://exampleandroid/test?data=dsads"))
.setDomainUriPrefix("https://App_Name.page.link")
// Open links with this app on Android
.setAndroidParameters(new DynamicLink.AndroidParameters.Builder().build())
// Open links with com.example.ios on iOS
.setIosParameters(new DynamicLink.IosParameters.Builder("com.appinventiv.ios").build())
.buildDynamicLink();
dynamicLinkUri = dynamicLink.getUri();

Let's say that You want to create the following URL:
https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
For this you can do following
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("www.myawesomesite.com")
.appendPath("turtles")
.appendPath("types")
.appendQueryParameter("type", "1")
.appendQueryParameter("sort", "relevance")
.fragment("section-name");
String myUrl = builder.build().toString();

Related

Firebase Dynamic Link New Install Events

I want to get the event of New install or App open/re-open events in my Android App whenever user click on any dynamic link.
Following events are captured in Analytics as per documentation:
dynamic_link_first_open
dynamic_link_app_open
But I can't find any way to get these from sample listener.
I have found solution to my above question. Sharing details here.
Below code is tested from PlayStore also.
You can get mentioned two events through pendingDynamicLinkData callback object received from addOnSuccessListener.
Complete code to get link and associated Dynamic link data here.
FirebaseDynamicLinks.getInstance()
.getDynamicLink(getIntent())
.addOnSuccessListener(this, pendingDynamicLinkData -> {
// Get deep link from result (may be null if no link is found)
try {
Uri deepLink = null;
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.getLink();
sendInstallDetailToAPI(pendingDynamicLinkData.getExtensions());
}
CgUtils.showLog(TAG, "getDynamicLink:onSuccess" + deepLink);
} catch (Exception e) {
CgUtils.showLog(TAG, "getDynamicLink:onFailure" + e);
}
})
.addOnFailureListener(this, e -> CgUtils.showLog(TAG, "getDynamicLink:onFailure" + e));
Below method to send the Dynamic Link data to your backend API if you want.
private void sendInstallDetailToAPI(Bundle deepBundle) {
Bundle deepLinkData = deepBundle.getBundle("scionData");
if (deepLinkData != null) {
Bundle appReOpenBundle = deepLinkData.getBundle("dynamic_link_app_open");
boolean isInstall = false;
String medium = "", source = "", campaign = "", shortLink = "";
if (appReOpenBundle != null) {
medium = appReOpenBundle.getString("medium", "NA");
source = appReOpenBundle.getString("source", "NA");
campaign = appReOpenBundle.getString("campaign", "NA");
shortLink = appReOpenBundle.getString("dynamic_link_link_id", "NA");
}
Bundle appFirstOpenBundle = deepLinkData.getBundle("dynamic_link_first_open");
if (appFirstOpenBundle != null) {
isInstall = true;
medium = appFirstOpenBundle.getString("medium", "NA");
source = appFirstOpenBundle.getString("source", "NA");
campaign = appFirstOpenBundle.getString("campaign", "NA");
shortLink = appFirstOpenBundle.getString("dynamic_link_link_id", "NA");
}
// Send ABOVE detail to your respective APIs
}
}
Now If isInstall flag is true that means it's first time open after install else reopen.

check playerSSign fail

When verifying the signature, the background server displays {"rtnCode":-1,"errMsg":"check playerSSign fail"}
The data provided by the client is
if(huaweiid != null){
PlayersClient player = Games.getPlayersClient(this, huaweiid);
player.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
#Override
public void onSuccess(Player player) {
String ts = player.getSignTs();
String playerId = player.getPlayerId();
int playerLevel = player.getLevel();
String playerSign = player.getPlayerSign();
//String displayName = player.getDisplayName();
//Uri hiResImageUri = player.getHiResImageUri();
//Uri iconImageUri = player.getIconImageUri();
JSONObject jo = new JSONObject();
try {
jo.put("signTs", ts);
jo.put("playerId", playerId);
jo.put("playerLevel", playerLevel);
jo.put("playerSign", playerSign);
EditText ed = findViewById(R.id.editText);
ed.setText(jo.toString());
Log.i("huawei user info", jo.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("huawei user info", Objects.requireNonNull(e.getMessage()));
}
}
});
}
Use the preceding four data items and the following description document:
https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/verify-login-signature-0000001050123503-V5
An error always occurs during the verification in the background.
{"rtnCode":-1,"errMsg":"check playerSSign fail"}
appId/cpid is obtained from agconnect-services.json and agconnect-services.json is downloaded from the background.
what’s the reason?
The following table describes the typical setting errors of the input parameters. Please verify the parameter settings.
https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/faq-check-login-0000001050746133-V5

Add parameter to Firebase Dynamic Links

I want to let the user share a product from my app by clicking a button and sending other potential users links like
www.myapp.com/offer/123
there, "123" must be generated at the moment the user click the button in order to, later in time, hanle it with
FirebaseDynamicLinks.getInstance()
.getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
Uri deepLink;
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.getLink();
but unfortunetly I am unable to pass a parameter.
String link = "http://www.myapp.com/offer/123";
Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse(link))
.setDynamicLinkDomain("fgd3e.app.goo.gl")
.buildShortDynamicLink()
.addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() {
#Override
public void onComplete(#NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful()) {
// Short link created
Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();
Can someone teach me how to create a dynamic link at runtime with custom parameters in order to re direct the target user to specific product detail?
SHORT ANSWER: Using query parameters instead of path variables you could use the getQueryParameter method from the Uri object returned by pendingDynamicLinkData.getLink()
What i've been doing is using query parameters instead of path variables.
Instead of sending http://www.myapp.com/offer/123, i'm sending something like http://www.myapp.com/?offer=123
To add parameters dynamically i'm just concatenating strings: "http://www.myapp.com/?offer=" + myValue
This URL is in turn a query parameter of the dynamic link created in firebase:
String url = "https://YourDynamicLinkIdentifier.app.goo.gl/?link=https://myapp.com?offer="
+ myOfferVar
+ "&apn=com.your.apn"; // << Dont forget to change this too
And this resulting URL is the one i send to the url shortener.
Then in the callback onSuccess(PendingDynamicLinkData pendingDynamicLinkData) call getLink() of pendingDynamicLinkData as you're already doing.
Now that you have a Uri object, you can easily get the parameter by calling the method getQueryParameter("offer").
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.getLink();
String offerKey = deepLink.getQueryParameter("offer");
NOTE: In case you still prefer to use the path variable, you could get the last segment of the Uri path. See How to obtain the last path segment of an uri
You need to use long deep link to send parameters.
Example:
1) link for opening the app by google play testing url:
https://xx.page.link/?link=https://xx.com/invitation/?id=2&apn=com.xx.app&afl=https://play.google.com/apps/testing/com.xx.app
2) receving the parameter:
FirebaseDynamicLinks.getInstance()
.getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
Uri deepLink = null;
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.getLink();
String paramValue = deepLink.getQueryParameters("id").get(0)); // it will get "2" as a value
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Splash", "getDynamicLink:onFailure", e);
}
});

How get extra parameter from dynamic link using Firebase?

I have created dynamic link manually and i set some additional parameters on the link, like this: https://XXXXX.goo.gl/?link=https%3A%2F%2Fairbanq.send.com%2Fsendmoney&apn=com.xxxx.xxxx&amv=1&username=Adri&amount=7.00
But when the app is opened i just get: "https:// airbanq.send.com/sendmoney"
without the addiotional parameters
i am using this sample code
https://github.com/firebase/quickstart-android/tree/master/dynamiclinks
any help please,
Thanks
My code
public String buildDeepLink() {
// Get the unique appcode for this app.
String appCode = AirBanqApp.mContext.getString(R.string.app_code);
// Get this app's package name.
String packageName = AirBanqApp.mContext.getPackageName();
// Build the link with all required parameters
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(appCode + ".app.goo.gl")
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
// If the deep link is used in an advertisement, this value must be set to 1.
if (isAd) {
builder.appendQueryParameter("ad", "1");
}
// Minimum version is optional.
if (minVersion > 0) {
builder.appendQueryParameter("amv", Integer.toString(minVersion));
}
if (!TextUtils.isEmpty(androidLink)) {
builder.appendQueryParameter("al", androidLink);
}
if (!TextUtils.isEmpty(playStoreAppLink)) {
builder.appendQueryParameter("afl", playStoreAppLink);
}
if (!customParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : customParameters.entrySet()) {
builder.appendQueryParameter(parameter.getKey(), parameter.getValue());
}
}
// Return the completed deep link.
return builder.build().toString();
}
Thats was my solution
i solved my issue, i assumed the "apn", "username" and "amount" they were part of the parameter "LINK" in the url, but no when i add the "&" i am adding parts to the main url, to add parameters to the "LINK" field i need to create first the url like this
https://airbanq.send.com/sendmoney?username=Adri&amount=7.00
then use URLEncoder.encode(queryParameters.toString(), "UTF-8");
to generate this
https%3A%2F%2Fairbanq.send.com%2Fsendmoney%253Fusername%253DAdri%2526amount%253D7.00
and then append to main url
https://xxxx.app.goo.gl/?link=https%3A%2F%2Fairbanq.send.com%2Fsendmoney%253Fusername%253DAdri%2526amount%253D7.00&apn=com.airbanq.airbanqapp&amv=1
public String buildDeepLink() {
// Get the unique appcode for this app.
String appCode = AirBanqApp.mContext.getString(R.string.app_code);
// Get this app's package name.
String packageName = AirBanqApp.mContext.getPackageName();
String queryParamters = "";
try {
queryParamters = generateQueryParameters();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(queryParamters)) {
deepLink = deepLink + queryParamters;
}
// Build the link with all required parameters
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(appCode + ".app.goo.gl")
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
// If the deep link is used in an advertisement, this value must be set to 1.
if (isAd) {
builder.appendQueryParameter("ad", "1");
}
// Minimum version is optional.
if (minVersion > 0) {
builder.appendQueryParameter("amv", Integer.toString(minVersion));
}
if (!TextUtils.isEmpty(androidLink)) {
builder.appendQueryParameter("al", androidLink);
}
if (!TextUtils.isEmpty(playStoreAppLink)) {
builder.appendQueryParameter("afl", playStoreAppLink);
}
// Return the completed deep link.
return builder.build().toString();
}
private String generateQueryParameters() throws UnsupportedEncodingException {
StringBuilder queryParameters = new StringBuilder();
//server purposes
queryParameters.append("?*code*");
if (!customParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : customParameters.entrySet()) {
queryParameters.append(String.format("&%1s=%2s", parameter.getKey(), parameter.getValue()));
}
}
return URLEncoder.encode(queryParameters.toString(), "UTF-8");
}
The official answer is that you need to escape/encode a URL string so that it can be safely placed inside a URL query.
I wish Firebase dynamic links would just say that about the link.
For Golang:
url.QueryEscape(urlstring)

Posting data from android app on my Twitter's account as tweet

I'm trying to post my data through android app on my twitter account so how should i do it.
i have tried a way, below is the code, and in that it is showing the data on my account and i need to click on the tweet button to get it tweeted. So can i know how to post it directly without asking me to tweet. Like Four Square app
public void open(View view){
String text = "Share Your Experiance ....!!!";
String url = "twitter://post?message=";
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url + Uri.encode(text)));
startActivity(i);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(this, "Can't send tweet! Please install twitter...", 2).show();
}
Thanks in Advance !!!
Firstly you have to check are you logged with twitter or not after as your condition you can apply this snippet code.
I think you follow the all basics for twitter integration in your code.
public void uploadPic(String message, String getImgUrl)
throws Exception {
try {
System.out.println(" ON UPLOAD PIC FUNCTION getImgUrl "+getImgUrl);
// URL url = new URL("http://faveplatewebservice.siplstudio.com/uploads/big_dish/oooo14n7464rO4_thumb.png");
URL url = new URL(getImgUrl);
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StatusUpdate status = new StatusUpdate("Check Out FavPlates on appstore, which offers you to add and find exciting dishes near you. "+message);
//status.setMedia(file);
status.setMedia("Check Out FavPlates on appstore, which offers you to add and find exciting dishes near you. "+message, in);
mTwitter.updateStatus(status);
} catch (TwitterException e) {
Log.d("TAG", "Pic Upload error" + e.getExceptionCode());
throw e;
}
}
hope it will help you!!
If you stuck anywhere then inform me.
Thankss!!

Categories

Resources