diff --git a/Branch-SDK-Automation-TestBed/build.gradle b/Branch-SDK-Automation-TestBed/build.gradle index 2b92d7712..121d9b2ef 100644 --- a/Branch-SDK-Automation-TestBed/build.gradle +++ b/Branch-SDK-Automation-TestBed/build.gradle @@ -5,8 +5,16 @@ plugins { android { compileSdk 33 + signingConfigs { + debug { + keyAlias System.getenv("SIGNING_KEY_ALIAS") + keyPassword System.getenv("SIGNING_KEY_PASSWORD") + storeFile file("automationSigningKeys.jks") + storePassword System.getenv("SIGNING_STORE_PASSWORD") + } + } defaultConfig { - applicationId "io.branch.saas.sdk.testbed" + applicationId "io.branch.branchandroiddemo" minSdk 21 targetSdk 33 versionCode 1 @@ -25,7 +33,7 @@ android { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } - namespace 'io.branch.saas.sdk.testbed' + namespace 'io.branch.branchandroiddemo' } dependencies { @@ -40,4 +48,6 @@ dependencies { implementation 'com.intuit.sdp:sdp-android:1.0.6' implementation("com.google.android.gms:play-services-ads-identifier:18.0.1") + implementation("com.google.code.gson:gson:2.8.7") + implementation 'com.googlecode.json-simple:json-simple:1.1' } \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/AndroidManifest.xml b/Branch-SDK-Automation-TestBed/src/main/AndroidManifest.xml index a3073e2f4..fc70fa460 100644 --- a/Branch-SDK-Automation-TestBed/src/main/AndroidManifest.xml +++ b/Branch-SDK-Automation-TestBed/src/main/AndroidManifest.xml @@ -1,8 +1,9 @@ - + - + - - - + android:value="key_live_fBcbpexoE7Nu1ONlzfl1BilgsFcsZT8T" /> + android:value="key_test_hdcBLUy1xZ1JD0tKg7qrLcgirFmPPVJc" /> + android:value="false" /> - + - - - - + + + + + - - - + diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BUOData.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BUOData.java new file mode 100644 index 000000000..5b857a8c1 --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BUOData.java @@ -0,0 +1,9 @@ +package io.branch.branchandroiddemo; + +public class BUOData { + public String canonicalIdentifier, contentTitle, contentDesc, imageUrl, productName, + productBrand, productVariant, street, city, region, country, postalCode, + latitude, longitude, sku, rating, averageRating, maximumRating, + ratingCount, imageCaption, quantity, price, customMetadata, + contentSchema, currencyType, trackContentData, productCategory, productCondition; +} diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BranchEventData.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BranchEventData.java new file mode 100644 index 000000000..3a1f9928d --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BranchEventData.java @@ -0,0 +1,25 @@ +package io.branch.branchandroiddemo; + +public class BranchEventData { + + public String eventType; + public String event; + public String alias; + public String transactionId; + public String currency; + public String revenue; + public String shipping; + public String tax; + public String coupon; + public String affiliation; + public String description; + public String purchaseLocation; + public String availability; + public String additionalData; + public String searchQuery; + public String registrationId; + public String customEventProperty1; + public String customEventProperty2; + public String customData1; + public String customData2; +} diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BranchWrapper.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BranchWrapper.java new file mode 100644 index 000000000..6fa372539 --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/BranchWrapper.java @@ -0,0 +1,253 @@ +package io.branch.branchandroiddemo; + +import static android.content.Intent.getIntent; +import static androidx.core.content.ContextCompat.startActivity; + +import static java.security.AccessController.getContext; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.net.Uri; +import android.os.Build; +import android.text.TextUtils; +import android.util.Log; + +import org.json.JSONObject; + +import java.io.IOException; + +import io.branch.branchandroiddemo.activities.LogDataActivity; +import io.branch.branchandroiddemo.activities.ShowQRCodeActivity; +import io.branch.indexing.BranchUniversalObject; +import io.branch.referral.Branch; +import io.branch.referral.BranchError; +import io.branch.referral.QRCode.BranchQRCode; +import io.branch.referral.util.BranchEvent; +import io.branch.referral.util.LinkProperties; + +public class BranchWrapper { + + static BranchWrapper branchwrapper; + + public Context ctx; + + public BranchWrapper(Context pCtx) { + ctx = pCtx; + } + + public void showLogWindow(String message, boolean isError, Context ctx, String buttonType) { + + Intent intent = new Intent(ctx, LogDataActivity.class); + if (isError) { + intent.putExtra(Constants.STATUS, Constants.FAIL); + } else { + intent.putExtra(Constants.STATUS, Constants.SUCCESS); + } + intent.putExtra(Constants.TYPE, buttonType); + intent.putExtra(Constants.MESSAGE, message); + ctx.startActivity(intent); + } + + public void createDeepLink(Intent intent, Context ctx) { + Common.getInstance().clearLog(); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + BranchUniversalObject buo = testDataObj.getParamBUOObject(testDataStr); + LinkProperties lp = testDataObj.getParamLinkPropertiesObject(testDataStr); + + if (buo != null && lp != null) { + String url = buo.getShortUrl(ctx, lp); + showLogWindow("", false, ctx, Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK); + } else { + showLogWindow("Invalid Params (BUO / lp) ", true, ctx, Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK); + } + } else { + showLogWindow("Test Data : Null", true, ctx, Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK); + } + } + + public void nativeShare(Activity activity, Intent intent, Context ctx) { + Common.getInstance().clearLog(); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + BranchUniversalObject buo = testDataObj.getParamBUOObject(testDataStr); + LinkProperties lp = testDataObj.getParamLinkPropertiesObject(testDataStr); + + if (buo != null && lp != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { + Branch.getInstance().share(activity, buo, lp, new Branch.BranchNativeLinkShareListener() { + @Override + public void onLinkShareResponse(String sharedLink, BranchError error) { + Log.d("Native Share Sheet:", "Link Shared: " + sharedLink); + } + + @Override + public void onChannelSelected(String channelName) { + Log.d("Native Share Sheet:", "Channel Selected: " + channelName); + } + }, + "Sharing Branch Short URL", "Using Native Chooser Dialog"); + } else { + showLogWindow("Unsupported Version", false, ctx, Constants.UNKNOWN); + } + } else { + showLogWindow("Invalid Params (BUO / lp) ", true, ctx, Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK); + } + } else { + showLogWindow("Test Data : Null", true, ctx, Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK); + } + } + + public void logEvent(Intent intent, Context ctx){ + Common.getInstance().clearLog(); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + BranchUniversalObject buo = testDataObj.getParamBUOObject(testDataStr); + BranchEvent branchEvent = testDataObj.getBranchEventObject(testDataStr); + + if ( buo != null && branchEvent != null) { + branchEvent.addContentItems(buo); + branchEvent.logEvent(ctx); + showLogWindow("",false, ctx,Constants.TRACK_CONTENT); + } else { + showLogWindow("Invalid Params (BUO / event) ",true, ctx,Constants.TRACK_CONTENT); + } + } else { + showLogWindow( "Test Data : Null" , true, ctx,Constants.TRACK_CONTENT); + } + } + public void setIdentity(Intent intent, Context ctx){ + Common.getInstance().clearLog(); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + String userName = testDataObj.getUserName(testDataStr); + if ( userName != null && (userName.isEmpty() == false)) { + Branch.getInstance().setIdentity(userName); + } else { + showLogWindow("Invalid username.",true, ctx,Constants.TRACK_USER); + } + } else { + showLogWindow( "Test Data : Null" , true, ctx,Constants.TRACK_USER); + } + } + + public void delayInitializationIfRequired(Intent intent){ + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + Boolean delayInit = testDataObj.getBoolParamValue(testDataStr, "DelayInitialization"); + if ( delayInit) { + Branch.expectDelayedSessionInitialization(true); + } + } + } + + public void initSession(Activity activity, Intent intent, Context ctx){ + Common.getInstance().clearLog(); + intent.putExtra(Constants.FORCE_NEW_SESSION, true); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + String url = testDataObj.getParamValue(testDataStr, "URL"); + if ( url != null && (url.isEmpty() == false)) { + Uri uri = Uri.parse(url); + Branch.InitSessionBuilder initSessionBuilder = Branch.sessionBuilder(activity).withCallback(new Branch.BranchReferralInitListener() { + @Override + public void onInitFinished(JSONObject referringParams, BranchError error) { + if (error == null) { + Log.i("BRANCH SDK", referringParams.toString()); + } else { + Log.i("BRANCH SDK error", error.getMessage()); + } + showLogWindow("",false, ctx,Constants.INIT_SESSION); + } + }).withData(uri); + initSessionBuilder.init(); + } else { + showLogWindow("Invalid URL.",true, ctx,Constants.INIT_SESSION); + } + } else { + showLogWindow( "Test Data : Null" , true, ctx,Constants.INIT_SESSION); + } + } + + public void setDMAParams(Intent intent){ + + Common.getInstance().clearLog(); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + + TestData testDataObj = new TestData(); + boolean eeaRegion = testDataObj.getBoolParamValue(testDataStr,"dma_eea"); + boolean adPersonalizationConsent = testDataObj.getBoolParamValue(testDataStr,"dma_ad_personalization"); + boolean adUserDataUsageConsent = testDataObj.getBoolParamValue(testDataStr,"dma_ad_user_data"); + + Branch.getInstance().setDMAParamsForEEA(eeaRegion, adPersonalizationConsent, adUserDataUsageConsent); + + } else { + showLogWindow( "Test Data : Null" , true, ctx,Constants.SET_DMA_Params); + } + } + + public void getQRCode(Activity activity, Intent intent, Context ctx){ + Common.getInstance().clearLog(); + String testDataStr = intent.getStringExtra("testData"); + Log.d("Branch SDK", "Intent extra 'testData:'\n" + testDataStr); + if (testDataStr != null) { + TestData testDataObj = new TestData(); + BranchUniversalObject buo = testDataObj.getParamBUOObject(testDataStr); + LinkProperties lp = testDataObj.getParamLinkPropertiesObject(testDataStr); + + if (buo != null && lp != null) { + Log.e("qr code","create qr code"); + BranchQRCode qrCode = new BranchQRCode() //All QR code settings are optional + .setCodeColor("#a4c639") + .setBackgroundColor(Color.WHITE) + .setMargin(1) + .setWidth(512) + .setImageFormat(BranchQRCode.BranchImageFormat.PNG) + .setCenterLogo("https://cdn.branch.io/branch-assets/1598575682753-og_image.png"); + try { + qrCode.getQRCodeAsImage(activity, buo, lp, new BranchQRCode.BranchQRCodeImageHandler() { + @Override + public void onSuccess(Bitmap qrCodeImage) { + + //Do something with the QR code here. + Log.e("qr code","generated"); + Common.qrCodeImage = qrCodeImage; + Intent qrIntent = new Intent(activity, ShowQRCodeActivity.class); + ctx.startActivity(qrIntent); + } + + @Override + public void onFailure(Exception e) { + Log.d("Failed to get QR code", String.valueOf(e)); + showLogWindow("Failed to get QR code" , true, ctx, Constants.CREATE_QR_CODE); + + } + }); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + showLogWindow("Invalid Params (BUO / lp) ", true, ctx, Constants.CREATE_QR_CODE); + } + } else { + showLogWindow("Test Data : Null", true, ctx, Constants.CREATE_QR_CODE); + } + } +} diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/Common.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/Common.java similarity index 72% rename from Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/Common.java rename to Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/Common.java index 15902eddc..289ff9684 100644 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/Common.java +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/Common.java @@ -1,11 +1,7 @@ -package io.branch.saas.sdk.testbed; +package io.branch.branchandroiddemo; -import android.content.Context; import android.graphics.Bitmap; - -import androidx.appcompat.app.AlertDialog; - -import io.branch.saas.sdk.testbed.listeners.DialogClickListener; +import android.util.Log; import java.io.BufferedReader; import java.io.IOException; @@ -31,25 +27,6 @@ public static Common getInstance() { return common; } - public void showDialogBox(String title, String message, Context context, DialogClickListener dialogClickListener) { - AlertDialog.Builder builder = new AlertDialog.Builder(context); - //Uncomment the below code to Set the message and title from the strings.xml file -// builder.setMessage(message);// .setTitle(R.string.dialog_title); - - //Setting message manually and performing action on button click - builder.setMessage(message) - .setCancelable(false) - .setPositiveButton("OK", (dialog, id) -> { - dialog.dismiss(); - dialogClickListener.onDialogDismissed(); - }); - //Creating dialog box - AlertDialog alert = builder.create(); - //Setting the title manually - alert.setTitle(title); - alert.show(); - } - public String readLogData() { Process process = null; try { @@ -100,6 +77,12 @@ private ArrayList printResults(Process process) { public void clearLog() { try { Runtime.getRuntime().exec("logcat -c"); + try { + Thread.sleep(1000); + } + catch (InterruptedException e) { + Log.i("BRANCH SDK", e.getMessage()); + } } catch (IOException e) { e.printStackTrace(); } diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/Constants.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/Constants.java similarity index 58% rename from Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/Constants.java rename to Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/Constants.java index 606b3a623..26b7f81de 100644 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/Constants.java +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/Constants.java @@ -1,22 +1,8 @@ -package io.branch.saas.sdk.testbed; +package io.branch.branchandroiddemo; public interface Constants { - String CONTENT_TITLE = "ContentTitle"; - String CONTENT_DESC = "ContentDesc"; - String IMAGE_URL = "ImageUrl"; - String CHANNEL = "Channel"; - String FEATURE = "Feature"; - String CAMPAIGN = "Champaign"; - String STAGE = "Stage"; - String DESKTOP_URL = "DesktopUrl"; - String ADDITIONAL_DATA = "AdditionalData"; - String BUO_REFERENCE = "BUOReference"; - String CREATE_DEEPLINK = "CreateDeeplink"; String ANDROID_URL = "branch"; - String IOS_URL = "iOSUrl"; String BUO_REFERENCE_AND_CREATE_DEP_LINK = "BUOReferenceAndCreateDeeplink"; - String CREATE_SHARE_LINK = "CreateShareLink"; - String CREATE_NATIVE_SHARE_LINK = "CreateNativeShareLink"; String TYPE = "type"; String CREATE_SEND_NOTIFICATION = "CreateSendNotification"; String CREATE_SEND_READ_DEEP_LINK = "CreateReadDeepLink"; @@ -33,4 +19,7 @@ public interface Constants { String AFTER_READ_DEEP_LINK = "AfterReadDeepLink"; String TRACK_CONTENT_DATA = "TrackContentData"; String CREATE_QR_CODE = "CreateQRCode"; + String SET_DMA_Params = "SetDMAParams"; + String INIT_SESSION = "InitSession"; + String UNKNOWN = "Unknown"; } diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/LinkPropertiesData.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/LinkPropertiesData.java new file mode 100644 index 000000000..f8abd258d --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/LinkPropertiesData.java @@ -0,0 +1,5 @@ +package io.branch.branchandroiddemo; + +public class LinkPropertiesData { + public String channelName, feature, campaign, stage, desktopUrl, androidUrl, iOSUrl, additionalData, centerLogo; +} diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/TestData.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/TestData.java new file mode 100644 index 000000000..94e1bdb7c --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/TestData.java @@ -0,0 +1,182 @@ +package io.branch.branchandroiddemo; + +import android.text.TextUtils; +import android.util.Log; + +import com.google.gson.Gson; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.util.Calendar; + +import io.branch.indexing.BranchUniversalObject; +import io.branch.referral.util.BRANCH_STANDARD_EVENT; +import io.branch.referral.util.BranchContentSchema; +import io.branch.referral.util.BranchEvent; +import io.branch.referral.util.ContentMetadata; +import io.branch.referral.util.CurrencyType; +import io.branch.referral.util.LinkProperties; +import io.branch.referral.util.ProductCategory; + +public class TestData { + + public BranchUniversalObject getParamBUOObject(String testData){ + BranchUniversalObject buoObject = null; + try { + JSONObject testDataObj = null; + + testDataObj = (JSONObject) new JSONParser().parse(testData); + + if (testDataObj.containsKey("BUOData")){ + JSONObject j = (JSONObject) testDataObj.get("BUOData"); + + ContentMetadata contentMetadata = null; + Gson gson = new Gson(); + BUOData buoData = gson.fromJson(j.toString(), BUOData.class); + + if (buoData != null) { + contentMetadata = new ContentMetadata() + .setProductName(buoData.productName) + .setProductBrand(buoData.productBrand) + .setProductVariant(buoData.productVariant) + .setProductCondition(TextUtils.isEmpty(buoData.productCondition) ? null : ContentMetadata.CONDITION.valueOf(buoData.productCondition)) + .setProductCategory(TextUtils.isEmpty(buoData.productCategory) ? null : ProductCategory.valueOf(buoData.productCategory)) + .setAddress(buoData.street, buoData.city, buoData.region, buoData.country, buoData.postalCode) + .setLocation(TextUtils.isEmpty(buoData.latitude) ? null : Double.parseDouble(buoData.latitude), TextUtils.isEmpty(buoData.longitude) ? null : Double.parseDouble(buoData.longitude)) + .setSku(buoData.sku) + .setRating(TextUtils.isEmpty(buoData.rating) ? null : Double.parseDouble(buoData.rating), + TextUtils.isEmpty(buoData.averageRating) ? null : Double.parseDouble(buoData.averageRating), + TextUtils.isEmpty(buoData.maximumRating) ? null : Double.parseDouble(buoData.maximumRating), + TextUtils.isEmpty(buoData.ratingCount) ? null : Integer.parseInt(buoData.ratingCount)) + .addImageCaptions(buoData.imageCaption) + .setQuantity(TextUtils.isEmpty(buoData.quantity) ? null : Double.parseDouble(buoData.quantity)) + .setPrice(TextUtils.isEmpty(buoData.price) ? null : Double.parseDouble(buoData.price), TextUtils.isEmpty(buoData.currencyType) ? CurrencyType.USD : CurrencyType.valueOf(buoData.currencyType)) + .setContentSchema(TextUtils.isEmpty(buoData.contentSchema) ? null : BranchContentSchema.valueOf(buoData.contentSchema)) + .addCustomMetadata("Custom_Content_metadata_key1", buoData.customMetadata); + + buoObject = new BranchUniversalObject() + .setCanonicalIdentifier(buoData.canonicalIdentifier) + .setTitle(buoData.contentTitle) + .setContentDescription(buoData.contentDesc) + .setContentImageUrl(buoData.imageUrl) + .setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC) + .setLocalIndexMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC) + .setContentMetadata(contentMetadata); + } + } + Log.i("BRANCH SDK error", "No BUO"); + } catch (ParseException e) { + System.out.println("position: " + e.getPosition()); + System.out.println(e); + } + return buoObject; + } + public LinkProperties getParamLinkPropertiesObject(String testData){ + LinkProperties linkProperties = null; + try { + JSONObject testDataObj = null; + testDataObj = (JSONObject) new JSONParser().parse(testData); + if (testDataObj.containsKey("CreateLinkReference")) { + JSONObject lpJSONObj = (JSONObject) testDataObj.get("CreateLinkReference"); + Gson gson = new Gson(); + LinkPropertiesData lpData = gson.fromJson(lpJSONObj.toString(), LinkPropertiesData.class); + if (lpData != null) { + linkProperties = new LinkProperties() + .setChannel(TextUtils.isEmpty(lpData.channelName) ? null : lpData.channelName) + .setFeature(TextUtils.isEmpty(lpData.feature) ? null : lpData.feature) + .setCampaign(TextUtils.isEmpty(lpData.campaign) ? null : lpData.campaign) + .setStage(TextUtils.isEmpty(lpData.stage) ? null : lpData.stage) + .addControlParameter("$desktop_url", TextUtils.isEmpty(lpData.desktopUrl) ? null : lpData.desktopUrl) + .addControlParameter("$android_url", TextUtils.isEmpty(lpData.androidUrl) ? null : lpData.androidUrl) + .addControlParameter("$fallback_url", TextUtils.isEmpty(lpData.androidUrl) ? null : lpData.androidUrl) + .addControlParameter("custom", TextUtils.isEmpty(lpData.additionalData) ? null : lpData.additionalData) + .addControlParameter("$ios_url", TextUtils.isEmpty(lpData.iOSUrl) ? null : lpData.iOSUrl) + .addControlParameter("custom_random", Long.toString(Calendar.getInstance().getTimeInMillis())); + } + } + } catch (ParseException pe) { + System.out.println("position: " + pe.getPosition()); + System.out.println(pe); + } catch (Exception e) { + Log.i("BRANCH SDK error", e.toString()); + } + + return linkProperties; + } + + public BranchEvent getBranchEventObject(String testData){ + BranchEvent branchEvent = null; + try { + JSONObject testDataObj = null; + testDataObj = (JSONObject) new JSONParser().parse(testData); + if (testDataObj.containsKey("TrackContentData")) { + JSONObject evJSONObj = (JSONObject) testDataObj.get("TrackContentData"); + Gson gson = new Gson(); + BranchEventData eventData = gson.fromJson(evJSONObj.toString(), BranchEventData.class); + if (eventData != null) { + branchEvent = new BranchEvent(BRANCH_STANDARD_EVENT.valueOf(TextUtils.isEmpty(eventData.event) ? BRANCH_STANDARD_EVENT.ADD_TO_CART.toString() : eventData.event)); + } + } + } catch (ParseException pe) { + System.out.println("position: " + pe.getPosition()); + System.out.println(pe); + } catch (Exception e) { + Log.i("BRANCH SDK error", e.toString()); + } + + return branchEvent; + } + + public String getUserName(String testData){ + try { + JSONObject testDataObj = null; + testDataObj = (JSONObject) new JSONParser().parse(testData); + if (testDataObj.containsKey("UserName")) { + String username = (String) testDataObj.get("UserName"); + return username; + } + } catch (ParseException pe) { + System.out.println("position: " + pe.getPosition()); + System.out.println(pe); + } catch (Exception e) { + Log.i("BRANCH SDK error", e.toString()); + } + return null; + } + + public String getParamValue(String testData, String key){ + try { + JSONObject testDataObj = null; + testDataObj = (JSONObject) new JSONParser().parse(testData); + if (testDataObj.containsKey(key)) { + String value = (String) testDataObj.get(key); + return value; + } + } catch (ParseException pe) { + System.out.println("position: " + pe.getPosition()); + System.out.println(pe); + } catch (Exception e) { + Log.i("BRANCH SDK error", e.toString()); + } + return null; + } + + public Boolean getBoolParamValue(String testData, String key){ + try { + JSONObject testDataObj = null; + testDataObj = (JSONObject) new JSONParser().parse(testData); + if (testDataObj.containsKey(key)) { + Boolean boolValue = (Boolean) testDataObj.get(key); + return boolValue; + } + } catch (ParseException pe) { + System.out.println("position: " + pe.getPosition()); + System.out.println(pe); + } catch (Exception e) { + Log.i("BRANCH SDK error", e.toString()); + } + return false; + } +} diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/LogDataActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/LogDataActivity.java new file mode 100644 index 000000000..90490233b --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/LogDataActivity.java @@ -0,0 +1,56 @@ +package io.branch.branchandroiddemo.activities; + +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import io.branch.branchandroiddemo.Common; +import io.branch.branchandroiddemo.Constants; +import io.branch.branchandroiddemo.R; + +public class LogDataActivity extends AppCompatActivity { + + private String clickType; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_log_data); + + String clickType = getIntent().getStringExtra(Constants.TYPE); + String message = getIntent().getStringExtra(Constants.MESSAGE); + String logData = ""; + + if((message != null) && ((message.isEmpty() == false) || (message.trim().isEmpty() == false))){ + logData = message; + } else if (clickType == null || clickType.isEmpty() || clickType.trim().isEmpty()) { + logData = "Unknown Button clicked"; + } else if (clickType.equalsIgnoreCase(Constants.UNKNOWN )){ + logData = "This feature is not yet implemented."; + } else { + logData = Common.getInstance().readLogData(); + Log.d("LogData", "" + logData); + } + + TextView tvLogData = findViewById(R.id.tv_log_data); + tvLogData.setText(logData); + + findViewById(R.id.bt_submit).setOnClickListener(view -> { + finish(); + }); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + } +} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/MainActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/MainActivity.java new file mode 100644 index 000000000..3e22afbc9 --- /dev/null +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/MainActivity.java @@ -0,0 +1,96 @@ +package io.branch.branchandroiddemo.activities; + +import io.branch.branchandroiddemo.BranchWrapper; + +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.ToggleButton; + +import androidx.appcompat.app.AppCompatActivity; + +import io.branch.branchandroiddemo.BranchWrapper; +import io.branch.indexing.BranchUniversalObject; +import io.branch.referral.Branch; +import io.branch.referral.BranchError; +import io.branch.referral.BranchLogger; +import io.branch.referral.util.LinkProperties; +import io.branch.branchandroiddemo.Common; +import io.branch.branchandroiddemo.Constants; +import io.branch.branchandroiddemo.R; +import io.branch.branchandroiddemo.TestData; + +public class MainActivity extends AppCompatActivity implements View.OnClickListener { + private Button btCreateDeepLink, btNativeShare, btTrackUser, + btCreateQrCode, btSetDMAParams, btLogEvent, btReadLogs, btInitSession; + private TextView tvMessage, tvUrl; + ToggleButton trackingCntrlBtn; + + BranchWrapper branchWrapper; + protected void initialize(){ + btCreateDeepLink = findViewById(R.id.bt_create_deep_link); + btNativeShare = findViewById(R.id.bt_native_share); + tvMessage = findViewById(R.id.tv_message); + tvUrl = findViewById(R.id.tv_url); + btCreateQrCode = findViewById(R.id.bt_create_qr_code); + btSetDMAParams = findViewById(R.id.bt_set_dma_params); + btLogEvent = findViewById(R.id.bt_logEvent_with_callback); + btReadLogs = findViewById(R.id.bt_Read_Logs); + btTrackUser = findViewById(R.id.bt_track_user); + btInitSession = findViewById(R.id.bt_init_session); + trackingCntrlBtn = findViewById(R.id.tracking_cntrl_btn); + + btCreateDeepLink.setOnClickListener(this); + btNativeShare.setOnClickListener(this); + btCreateQrCode.setOnClickListener(this); + btSetDMAParams.setOnClickListener(this); + btLogEvent.setOnClickListener(this); + btReadLogs.setOnClickListener(this); + btTrackUser.setOnClickListener(this); + btInitSession.setOnClickListener(this); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + Common.getInstance().clearLog(); + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + initialize(); + + branchWrapper = new BranchWrapper(getApplicationContext()); + branchWrapper.delayInitializationIfRequired(getIntent()); + + Branch.enableLogging(BranchLogger.BranchLogLevel.VERBOSE); + + trackingCntrlBtn.setChecked(Branch.getInstance().isTrackingDisabled()); + trackingCntrlBtn.setOnCheckedChangeListener((buttonView, isChecked) -> Branch.getInstance().disableTracking(isChecked)); + } + + @Override + public void onClick(View view) { + + if (view == btCreateDeepLink) { + branchWrapper.createDeepLink(getIntent(), MainActivity.this); + } else if (view == btNativeShare) { + branchWrapper.nativeShare(this, getIntent(), MainActivity.this); + } else if (view == btLogEvent) { + branchWrapper.logEvent(getIntent(), MainActivity.this); + } else if (view == btTrackUser) { + branchWrapper.setIdentity(getIntent(), MainActivity.this); + } else if (view == btSetDMAParams) { + branchWrapper.setDMAParams(getIntent()); + } else if (view == btInitSession) { + branchWrapper.initSession(this, getIntent(), MainActivity.this); + } else if (view == btReadLogs) { + branchWrapper.showLogWindow("",false, this, Constants.LOG_DATA); + } else if (view == btCreateQrCode) { + branchWrapper.getQRCode(this, getIntent(), MainActivity.this); + }else { + branchWrapper.showLogWindow("",false, this, Constants.UNKNOWN); + } + } +} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/ShowQRCodeActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/ShowQRCodeActivity.java similarity index 84% rename from Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/ShowQRCodeActivity.java rename to Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/ShowQRCodeActivity.java index 452bdd8f4..d7279b556 100644 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/ShowQRCodeActivity.java +++ b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/branchandroiddemo/activities/ShowQRCodeActivity.java @@ -1,4 +1,4 @@ -package io.branch.saas.sdk.testbed.activities; +package io.branch.branchandroiddemo.activities; import androidx.appcompat.app.AppCompatActivity; @@ -6,8 +6,8 @@ import android.view.View; import android.widget.ImageView; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.R; +import io.branch.branchandroiddemo.Common; +import io.branch.branchandroiddemo.R; public class ShowQRCodeActivity extends AppCompatActivity { diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/BUOReferenceActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/BUOReferenceActivity.java deleted file mode 100644 index 2d25e5d90..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/BUOReferenceActivity.java +++ /dev/null @@ -1,128 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.content.Intent; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; - -import io.branch.indexing.BranchUniversalObject; -import io.branch.referral.util.BranchEvent; -import io.branch.referral.util.ContentMetadata; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; -import io.branch.saas.sdk.testbed.listeners.DialogClickListener; - -public class BUOReferenceActivity extends AppCompatActivity implements View.OnClickListener { - private EditText etTitle, etContentDescription, etImageUrl, etCanonicalIdentifier; - private String clickType; - private Button btSubmit, btAddMeta; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_buoreference); - clickType = getIntent().getStringExtra(Constants.TYPE); - getSupportActionBar().setTitle("Create BUO"); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - etCanonicalIdentifier = findViewById(R.id.et_canonicalIdentifier); - etTitle = findViewById(R.id.et_title); - etContentDescription = findViewById(R.id.et_content_description); - etImageUrl = findViewById(R.id.et_image_url); - btSubmit = findViewById(R.id.bt_submit); - btAddMeta = findViewById(R.id.bt_add_metadata); - btSubmit.setOnClickListener(this); - btAddMeta.setOnClickListener(this); - } - - // this event will enable the back - // function to the button on press - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - if (item.getItemId() == android.R.id.home) { - this.finish(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onClick(View view) { - /*Intent intent = new Intent(); - Log.e("data",""+etTitle.getText()+" "+etContentDescription.getText() +" "+etImageUrl.getText()); - intent.putExtra(Constants.CONTENT_TITLE, etTitle.getText().toString()); - intent.putExtra(Constants.CONTENT_DESC, etContentDescription.getText().toString()); - intent.putExtra(Constants.IMAGE_URL, etImageUrl.getText().toString()); - setResult(RESULT_OK, intent); - finish();*/ - if (view == btSubmit) { - String canStr = etCanonicalIdentifier.getText().toString(); - String title = etTitle.getText().toString(); - String desc = etContentDescription.getText().toString(); - String imgUrl = etImageUrl.getText().toString(); - Common.branchUniversalObject = new BranchUniversalObject() - .setCanonicalIdentifier(TextUtils.isEmpty(canStr) ? null : canStr) - .setTitle(TextUtils.isEmpty(title) ? null : title) - .setContentDescription(TextUtils.isEmpty(desc) ? null : desc) - .setContentImageUrl(TextUtils.isEmpty(imgUrl) ? null : imgUrl) - .setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC) - .setLocalIndexMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC) - .setContentMetadata(Common.getInstance().contentMetadata == null ? new ContentMetadata().addCustomMetadata("key1", "value1") : Common.getInstance().contentMetadata); -// Common.branchUniversalObject.listOnGoogleSearch(this); -// new BranchEvent(BRANCH_STANDARD_EVENT.VIEW_ITEM).addContentItems(Common.branchUniversalObject).logEvent(this); - - if (Common.branchUniversalObject == null) { - Common.getInstance().showDialogBox("Fail", "Failed to create Content reference", BUOReferenceActivity.this, new DialogClickListener() { - @Override - public void onDialogDismissed() { - - } - }); - } else { - Common.getInstance().clearLog(); - if (!TextUtils.isEmpty(clickType) && clickType.equals(Constants.TRACK_CONTENT)) { - boolean logEvent = new BranchEvent(Common.getInstance().branchStandardEvent).addContentItems(Common.branchUniversalObject).logEvent(this); - Intent intent = new Intent(this, LogDataActivity.class); - intent.putExtra(Constants.TYPE, Constants.TRACK_CONTENT_DATA); - if (logEvent) { - intent.putExtra(Constants.STATUS, Constants.SUCCESS); - } else { - intent.putExtra(Constants.STATUS, Constants.FAIL); - } - startActivity(intent); - finish(); - return; - } -// Common.branchUniversalObject.listOnGoogleSearch(this); - Common.getInstance().showDialogBox("Success", "BranchUniversalObject reference created", BUOReferenceActivity.this, new DialogClickListener() { - @Override - public void onDialogDismissed() { - if (clickType.equals(Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK) - || clickType.equals(Constants.CREATE_SHARE_LINK) - || clickType.equals(Constants.CREATE_NATIVE_SHARE_LINK) - || clickType.equals(Constants.CREATE_SEND_NOTIFICATION) - || clickType.equals(Constants.CREATE_SEND_READ_DEEP_LINK) - || clickType.equals(Constants.NAVIGATE_TO_CONTENT) - || clickType.equals(Constants.TRACK_CONTENT) - || clickType.equals(Constants.HANDLE_LINKS) - || clickType.equals(Constants.CREATE_QR_CODE)) { - Intent intent = new Intent(BUOReferenceActivity.this, GenerateUrlActivity.class); - intent.putExtra(Constants.TYPE, clickType); - startActivity(intent); - } - finish(); - } - }); - } - } else if (view == btAddMeta){ - Intent intent = new Intent(BUOReferenceActivity.this, MetadataActivity.class); - startActivity(intent); - } - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/GenerateUrlActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/GenerateUrlActivity.java deleted file mode 100644 index 0d311d266..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/GenerateUrlActivity.java +++ /dev/null @@ -1,260 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.app.NotificationCompat; -import androidx.core.app.NotificationManagerCompat; - -import java.io.IOException; -import java.util.Calendar; - -import io.branch.indexing.BranchUniversalObject; -import io.branch.referral.Branch; -import io.branch.referral.BranchError; -import io.branch.referral.QRCode.BranchQRCode; -import io.branch.referral.SharingHelper; -import io.branch.referral.util.LinkProperties; -import io.branch.referral.util.ShareSheetStyle; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; - -public class GenerateUrlActivity extends AppCompatActivity implements View.OnClickListener { - private EditText etChannel, etFeature, etChampaign, etStage, - etDesktopUrl, etAdditionalData, etAndroidUrl, etIosUrl, etQrCodeLogoUrl; - private String clickType; - private final static String branchChannelID = "BranchChannelID"; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_generate_url); - getSupportActionBar().setTitle("Generate URL"); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - clickType = getIntent().getStringExtra(Constants.TYPE); - createNotificationChannel(); - - etChannel = findViewById(R.id.et_channel); - etChampaign = findViewById(R.id.et_campaign); - etFeature = findViewById(R.id.et_feature); - etStage = findViewById(R.id.et_stage); - etDesktopUrl = findViewById(R.id.et_desktop_url); - etAdditionalData = findViewById(R.id.et_additional_data); - etAndroidUrl = findViewById(R.id.et_android_url); - etIosUrl = findViewById(R.id.et_ios_url); - if (clickType.equals(Constants.CREATE_QR_CODE)) { - findViewById(R.id.til_qr_code_logo).setVisibility(View.VISIBLE); - etQrCodeLogoUrl = findViewById(R.id.et_qr_code_logo_url); - } - - Button btSubmit = findViewById(R.id.bt_submit); - btSubmit.setOnClickListener(this); - } - - // this event will enable the back - // function to the button on press - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - if (item.getItemId() == android.R.id.home) { - this.finish(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onClick(View view) { - Common.getInstance().clearLog(); - String channel = etChannel.getText().toString(); - String feature = etFeature.getText().toString(); - String champaign = etChampaign.getText().toString(); - String stage = etStage.getText().toString(); - String desktopUrl = etDesktopUrl.getText().toString(); - String androidUrl = etAndroidUrl.getText().toString(); - String additionalData = etAdditionalData.getText().toString(); - String iosUrl = etIosUrl.getText().toString(); - Common.lp = new LinkProperties() - .setChannel(TextUtils.isEmpty(channel) ? null : channel) - .setFeature(TextUtils.isEmpty(feature) ? null : feature) - .setCampaign(TextUtils.isEmpty(champaign) ? null : champaign) - .setStage(TextUtils.isEmpty(stage) ? null : stage) - .addControlParameter("$desktop_url", TextUtils.isEmpty(desktopUrl) ? null : desktopUrl) - .addControlParameter("$android_url", TextUtils.isEmpty(androidUrl) ? null : androidUrl) - .addControlParameter("custom", TextUtils.isEmpty(additionalData) ? null : additionalData) - .addControlParameter("$ios_url", TextUtils.isEmpty(iosUrl) ? null : iosUrl) - .addControlParameter("custom_random", Long.toString(Calendar.getInstance().getTimeInMillis())); - if (clickType.equals(Constants.CREATE_SHARE_LINK)) { - ShareSheetStyle shareSheetStyle = new ShareSheetStyle(this, "Check this out!", "This stuff is awesome: ") - .setCopyUrlStyle(getResources().getDrawable(android.R.drawable.ic_menu_send), "Copy", "Added to clipboard") - .setMoreOptionStyle(getResources().getDrawable(android.R.drawable.ic_menu_search), "Show more") - .addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK_MESSENGER) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.TWITTER) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.MESSAGE) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.FLICKR) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.GOOGLE_DOC) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.WHATS_APP) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.PINTEREST) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.HANGOUT) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.INSTAGRAM) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.WECHAT) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.SNAPCHAT) - .addPreferredSharingOption(SharingHelper.SHARE_WITH.GMAIL) - .setAsFullWidthStyle(true) - .setSharingTitle("Share With"); - Common.branchUniversalObject.showShareSheet(this, - Common.lp, - shareSheetStyle, - new Branch.ExtendedBranchLinkShareListener() { - @Override - public void onShareLinkDialogLaunched() { - } - - @Override - public void onShareLinkDialogDismissed() { - } - - @Override - public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) { - Log.e("BRANCH SDK", "link---> " + sharedLink); - } - - @Override - public void onChannelSelected(String channelName) { - Log.e("BRANCH SDK", "channelName-->" + channelName); - } - - @Override - public boolean onChannelSelected(String channelName, BranchUniversalObject buo, LinkProperties linkProperties) { - return false; - } - }); - } else if (clickType.equals(Constants.CREATE_NATIVE_SHARE_LINK)) { - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { - Branch.getInstance().share(this, Common.branchUniversalObject, Common.lp, new Branch.BranchNativeLinkShareListener() { - @Override - public void onLinkShareResponse(String sharedLink, BranchError error) { - Log.d("Native Share Sheet:", "Link Shared: " + sharedLink); - } - - @Override - public void onChannelSelected(String channelName) { - Log.d("Native Share Sheet:", "Channel Selected: " + channelName); - } - - }, - "Sharing Branch Short URL", "Using Native Chooser Dialog"); - } - - } else if (clickType.equals(Constants.CREATE_QR_CODE)) { - Log.e("qr code","create qr code"); - String qrCodeCenterLogoUrlStr = etQrCodeLogoUrl.getText().toString(); - BranchQRCode qrCode = new BranchQRCode() //All QR code settings are optional - .setCodeColor("#a4c639") - .setBackgroundColor(Color.WHITE) - .setMargin(1) - .setWidth(512) - .setImageFormat(BranchQRCode.BranchImageFormat.PNG) - .setCenterLogo(TextUtils.isEmpty(qrCodeCenterLogoUrlStr) ? null : qrCodeCenterLogoUrlStr); - try { - qrCode.getQRCodeAsImage(GenerateUrlActivity.this, Common.branchUniversalObject, Common.lp, new BranchQRCode.BranchQRCodeImageHandler() { - @Override - public void onSuccess(Bitmap qrCodeImage) { - - //Do something with the QR code here. - Log.e("qr code","generated"); - Common.qrCodeImage = qrCodeImage; - Intent intent = new Intent(GenerateUrlActivity.this, ShowQRCodeActivity.class); - startActivity(intent); - finish(); - } - - @Override - public void onFailure(Exception e) { - Log.d("Failed to get QR code", String.valueOf(e)); - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - Common.branchUniversalObject.generateShortUrl(this, Common.lp, (url, error) -> { - Intent intent = new Intent(GenerateUrlActivity.this, LogDataActivity.class); - if (error == null) { - intent.putExtra(Constants.STATUS, Constants.SUCCESS); - intent.putExtra(Constants.TYPE, clickType); - intent.putExtra(Constants.ANDROID_URL, url); - if (clickType.equals(Constants.CREATE_SEND_NOTIFICATION)) { - intent.putExtra(Constants.MESSAGE, "Url is generated.\n Notification sent successfully"); - showNotification(url); - } else if (clickType.equals(Constants.HANDLE_LINKS)) { - intent.putExtra(Constants.MESSAGE, "Url is generated.\n Here is the Short URL:" + url); - intent.putExtra(Constants.FORCE_NEW_SESSION, true); - } else { - intent.putExtra(Constants.MESSAGE, "Url is generated.\n Here is the Short URL:" + url); - } - } else { - intent.putExtra(Constants.STATUS, Constants.FAIL); - intent.putExtra(Constants.MESSAGE, "Unable to generate short url:" + error.getMessage()); - } - startActivity(intent); - finish(); - }); - } - } - - private void showNotification(String url) { - Intent intent = new Intent(GenerateUrlActivity.this, ReadDeepLinkActivity.class); - -// intent.setData(Uri.parse(url)); - intent.putExtra(Constants.ANDROID_URL, url); - intent.putExtra(Constants.FORCE_NEW_SESSION, true); - PendingIntent pendingIntent; - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { - pendingIntent = PendingIntent.getActivity(GenerateUrlActivity.this, 0, intent, PendingIntent.FLAG_IMMUTABLE); - } else { - pendingIntent = PendingIntent.getActivity(GenerateUrlActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - } - - NotificationCompat.Builder builder = new NotificationCompat.Builder(GenerateUrlActivity.this, branchChannelID) - .setSmallIcon(R.mipmap.ic_launcher) - .setContentTitle("BranchTest") - .setContentText(url) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setContentIntent(pendingIntent) - .setAutoCancel(true); - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(GenerateUrlActivity.this); - notificationManager.notify(1, builder.build()); - } - - private void createNotificationChannel() { - // Create the NotificationChannel, but only on API 26+ because - // the NotificationChannel class is new and not in the support library - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationChannel channel = new NotificationChannel(branchChannelID, "BranchChannel", NotificationManager.IMPORTANCE_DEFAULT); - channel.setDescription("Very interesting description"); - // Register the channel with the system; you can't change the importance - // or other notification behaviors after this - NotificationManager notificationManager = getSystemService(NotificationManager.class); - if (notificationManager == null) return; - notificationManager.createNotificationChannel(channel); - } - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/LogDataActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/LogDataActivity.java deleted file mode 100644 index f69a1c48b..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/LogDataActivity.java +++ /dev/null @@ -1,85 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.content.Intent; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; -import android.view.View; -import android.widget.TextView; - -import androidx.appcompat.app.AppCompatActivity; - -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; - -public class LogDataActivity extends AppCompatActivity { - - private String clickType; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_log_data); - clickType = getIntent().getStringExtra(Constants.TYPE); - findViewById(R.id.bt_submit).setOnClickListener(view -> { - if (!clickType.equals(Constants.TRACK_USER) && - !clickType.equals(Constants.CREATE_SEND_NOTIFICATION) && - !clickType.equals(Constants.LOG_DATA)) { - Intent intent; - switch (clickType) { - case Constants.CREATE_SEND_READ_DEEP_LINK: - intent = new Intent(LogDataActivity.this, UrlPreviewActivity.class); - break; - case Constants.HANDLE_LINKS: - intent = new Intent(LogDataActivity.this, ReadDeepLinkActivity.class); - intent.putExtra(Constants.TYPE, clickType); - intent.putExtra(Constants.FORCE_NEW_SESSION, true); - break; - case Constants.AFTER_READ_DEEP_LINK: - intent = new Intent(LogDataActivity.this, MainActivity.class); - break; - case Constants.TRACK_CONTENT_DATA: - intent = new Intent(LogDataActivity.this, GenerateUrlActivity.class); - intent.putExtra(Constants.TYPE, Constants.TRACK_CONTENT); - break; - default: - intent = new Intent(LogDataActivity.this, ReadDeepLinkActivity.class); - intent.putExtra(Constants.TYPE, clickType); - break; - } - intent.putExtra(Constants.ANDROID_URL, getIntent().getStringExtra(Constants.ANDROID_URL)); - startActivity(intent); - } - finish(); - }); - TextView tvSuccessFailTitle = findViewById(R.id.tv_success_fail_title); - TextView tvLogData = findViewById(R.id.tv_log_data); - String status = getIntent().getStringExtra(Constants.STATUS); - tvSuccessFailTitle.setText(getIntent().getStringExtra(Constants.STATUS)); - String message = getIntent().getStringExtra(Constants.MESSAGE); - if (status.equals(Constants.SUCCESS)) { - String logData = Common.getInstance().readLogData(); - tvLogData.setVisibility(View.VISIBLE); - Log.d("LogData", "" + logData); - if (!TextUtils.isEmpty(message)) { - tvLogData.setText(message + "\n\n" + logData); - } else { - tvLogData.setText(logData); - } - } else { - if (!TextUtils.isEmpty(message)) { - tvLogData.setText(message); - } - } - } - - @Override - public void onBackPressed() { - if (clickType.equals(Constants.AFTER_READ_DEEP_LINK)) { - Intent intent = new Intent(this, MainActivity.class); - startActivity(intent); - } - super.onBackPressed(); - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/MainActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/MainActivity.java deleted file mode 100644 index cf505082b..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/MainActivity.java +++ /dev/null @@ -1,143 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.content.Intent; -import android.os.Bundle; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.TextView; -import android.widget.ToggleButton; - -import androidx.appcompat.app.AppCompatActivity; - -import io.branch.referral.Branch; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; - -public class MainActivity extends AppCompatActivity implements View.OnClickListener { - private Button btBuoObj, btCreateDeepLink, btShare, btNativeShare, btTrackUser, - btReadDeepLink, btNotification, btBuoObjWithMeta, btNavigateToContent, btTrackContent, btHandleLinks, btCreateQrCode; - private TextView tvMessage, tvUrl; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - Branch.getInstance().setIdentity("automation_test_user"); - Branch.enableLogging(); - btBuoObj = findViewById(R.id.bt_buo_obj); - btCreateDeepLink = findViewById(R.id.bt_create_deep_link); - btShare = findViewById(R.id.bt_share); - btNativeShare = findViewById(R.id.bt_native_share); - btReadDeepLink = findViewById(R.id.bt_read_deep_link); - tvMessage = findViewById(R.id.tv_message); - tvUrl = findViewById(R.id.tv_url); - btBuoObjWithMeta = findViewById(R.id.bt_buo_obj_with_meta); - btNavigateToContent = findViewById(R.id.bt_navigate_to_content); - btTrackContent = findViewById(R.id.bt_track_content); - btCreateQrCode = findViewById(R.id.bt_create_qr_code); - - btHandleLinks = findViewById(R.id.bt_handle_links); - - ToggleButton trackingCntrlBtn = findViewById(R.id.tracking_cntrl_btn); - btBuoObj.setOnClickListener(this); - btCreateDeepLink.setOnClickListener(this); - btShare.setOnClickListener(this); - btNativeShare.setOnClickListener(this); - btTrackContent.setOnClickListener(this); - btHandleLinks.setOnClickListener(this); - btTrackUser = findViewById(R.id.bt_track_user); - btNotification = findViewById(R.id.bt_notification); - btNotification.setOnClickListener(this); - btTrackUser.setOnClickListener(this); - btReadDeepLink.setOnClickListener(this); - btBuoObjWithMeta.setOnClickListener(this); - btNavigateToContent.setOnClickListener(this); - btCreateQrCode.setOnClickListener(this); - trackingCntrlBtn.setChecked(Branch.getInstance().isTrackingDisabled()); - trackingCntrlBtn.setOnCheckedChangeListener((buttonView, isChecked) -> Branch.getInstance().disableTracking(isChecked)); - - - /*LinkProperties lp = new LinkProperties() - .setChannel("facebook") - .setFeature("sharing") - .setCampaign("content 123 launch") - .setStage("new user") - .addControlParameter("$desktop_url", "https://example.com/home") - .addControlParameter("custom", "data") - .addControlParameter("custom_random", Long.toString(Calendar.getInstance().getTimeInMillis())); - - buo.generateShortUrl(this, lp, new Branch.BranchLinkCreateListener() { - @Override - public void onLinkCreate(String url, BranchError error) { - if (error == null) { - Log.i("BRANCH SDK", "got my Branch link to share: " + url); - Toast.makeText(MainActivity.this, "link==>" + url, Toast.LENGTH_SHORT).show(); - } - } - });*/ - } - - @Override - public void onClick(View view) { - if (view == btBuoObj) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.BUO_REFERENCE); - startActivity(intent); - } else if (view == btCreateDeepLink) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK); - startActivity(intent); - } else if (view == btNativeShare) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.CREATE_NATIVE_SHARE_LINK); - startActivity(intent); - } else if (view == btShare) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.CREATE_SHARE_LINK); - startActivity(intent); - } else if (view == btTrackUser) { - Common.getInstance().clearLog(); - Branch.getInstance().setIdentity("automation_test_user", (referringParams, error) -> { - Intent intent = new Intent(MainActivity.this, LogDataActivity.class); - intent.putExtra(Constants.TYPE, Constants.TRACK_USER); - if (referringParams != null) { - intent.putExtra(Constants.MESSAGE,"Track User Data"); - Log.i("track user result-->", "" + referringParams); - intent.putExtra(Constants.STATUS, Constants.SUCCESS); - } else { - intent.putExtra(Constants.MESSAGE,"Failed to load Track User Data"); - intent.putExtra(Constants.STATUS, Constants.FAIL); - Log.i("track user error-->", "" + error.getMessage()); - } - startActivity(intent); - }); - } else if (view == btNotification) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.CREATE_SEND_NOTIFICATION); - startActivity(intent); - } else if (view == btReadDeepLink) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.CREATE_SEND_READ_DEEP_LINK); - startActivity(intent); - finish(); - } else if (view == btNavigateToContent) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.NAVIGATE_TO_CONTENT); - startActivity(intent); - } else if (view == btTrackContent) { - Intent intent = new Intent(this, TrackContentActivity.class); - startActivity(intent); - } else if (view == btCreateQrCode) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.CREATE_QR_CODE); - startActivity(intent); - } else if (view == btHandleLinks) { - Intent intent = new Intent(this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.HANDLE_LINKS); - startActivity(intent); - } - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/MetadataActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/MetadataActivity.java deleted file mode 100644 index 7a87da475..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/MetadataActivity.java +++ /dev/null @@ -1,161 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.os.Bundle; -import android.text.TextUtils; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.Spinner; - -import androidx.appcompat.app.AppCompatActivity; - -import io.branch.referral.util.BranchContentSchema; -import io.branch.referral.util.ContentMetadata; -import io.branch.referral.util.CurrencyType; -import io.branch.referral.util.ProductCategory; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.R; - -public class MetadataActivity extends AppCompatActivity { - private Spinner productCategory; - private Spinner productCondition; - private Spinner currencyType; - private Spinner contentSchema; - - private String productCategoryStr, conditionStr, currencyStr, contentSchemaStr; - - private EditText etProductName, etProductBrand, etProductVariant, etStreetName, etCity, - etRegion, etCountry, etPostalCode, etLongitude, etLatitude, etSku, etRating, - etAvgRating, etMaxRating, etRatingCount, - etImageCaption, etQuantity, etPrice, etCustomMetadata; - - private String productNameStr, productBrandStr, productVariantStr, streetNameStr, cityStr, - regionStr, countryStr, postalCodeStr, longitudeStr, latitudeStr, skuStr, ratingStr, - avgRatingStr, maxRatingStr, ratingCountStr, - imageCaptionStr, quantityStr, priceStr, customMetadataStr; - - private Button submitBtn; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_metadata); - - productCategory = findViewById(R.id.sp_product_category); - productCondition = findViewById(R.id.sp_product_condition); - currencyType = findViewById(R.id.sp_currency_type); - contentSchema = findViewById(R.id.sp_content_schema); - - etProductName = findViewById(R.id.et_product_name); - etProductBrand = findViewById(R.id.et_product_brand); - etProductVariant = findViewById(R.id.et_product_variant); - etStreetName = findViewById(R.id.et_street_name); - etCity = findViewById(R.id.et_city); - etRegion = findViewById(R.id.et_region_name); - etCountry = findViewById(R.id.et_country_name); - etPostalCode = findViewById(R.id.et_postal_code); - etLongitude = findViewById(R.id.et_longitude); - etLatitude = findViewById(R.id.et_latitude); - etSku = findViewById(R.id.et_setSku); - etRating = findViewById(R.id.et_rating); - etAvgRating = findViewById(R.id.et_avg_rating); - etMaxRating = findViewById(R.id.et_max_rating); - etRatingCount = findViewById(R.id.et_rating_count); - etImageCaption = findViewById(R.id.et_image_caption); - etQuantity = findViewById(R.id.et_quantity); - etPrice = findViewById(R.id.et_price); - etCustomMetadata = findViewById(R.id.et_add_custom_metadata); - - submitBtn = findViewById(R.id.bt_submit); - - - setSpinnerAdapter(R.array.product_category, productCategory, "productCategory"); - setSpinnerAdapter(R.array.product_condition, productCondition, "productCondition"); - setSpinnerAdapter(R.array.currency_type, currencyType, "currencyType"); - setSpinnerAdapter(R.array.content_schema, contentSchema, "contentSchema"); - - - submitBtn.setOnClickListener(view -> addMeta()); - - - } - - private void addMeta() { - productNameStr = etProductName.getText().toString(); - productBrandStr = etProductBrand.getText().toString(); - productVariantStr = etProductVariant.getText().toString(); - streetNameStr = etStreetName.getText().toString(); - cityStr = etCity.getText().toString(); - regionStr = etRegion.getText().toString(); - countryStr = etCountry.getText().toString(); - postalCodeStr = etPostalCode.getText().toString(); - longitudeStr = etLongitude.getText().toString(); - latitudeStr = etLatitude.getText().toString(); - skuStr = etSku.getText().toString(); - ratingStr = etRating.getText().toString(); - avgRatingStr = etAvgRating.getText().toString(); - maxRatingStr = etMaxRating.getText().toString(); - ratingCountStr = etRatingCount.getText().toString(); - imageCaptionStr = etImageCaption.getText().toString(); - quantityStr = etQuantity.getText().toString(); - priceStr = etPrice.getText().toString(); - customMetadataStr = etCustomMetadata.getText().toString(); - Common.getInstance().contentMetadata = new ContentMetadata() - .setProductName(productNameStr) - .setProductBrand(productBrandStr) - .setProductVariant(productVariantStr) - .setProductCondition(TextUtils.isEmpty(conditionStr) ? null : ContentMetadata.CONDITION.valueOf(conditionStr)) - .setProductCategory(TextUtils.isEmpty(productCategoryStr) ? null : ProductCategory.valueOf(productCategoryStr)) - .setAddress(streetNameStr, cityStr, regionStr, countryStr, postalCodeStr) - .setLocation(TextUtils.isEmpty(latitudeStr) ? null : Double.parseDouble(latitudeStr), TextUtils.isEmpty(longitudeStr) ? null : Double.parseDouble(longitudeStr)) - .setSku(skuStr) - .setRating(TextUtils.isEmpty(ratingStr) ? null : Double.parseDouble(ratingStr), - TextUtils.isEmpty(avgRatingStr) ? null : Double.parseDouble(avgRatingStr), - TextUtils.isEmpty(maxRatingStr) ? null : Double.parseDouble(maxRatingStr), - TextUtils.isEmpty(ratingCountStr) ? null : Integer.parseInt(ratingCountStr)) - .addImageCaptions(imageCaptionStr) - .setQuantity(TextUtils.isEmpty(quantityStr) ? null : Double.parseDouble(quantityStr)) - .setPrice(TextUtils.isEmpty(priceStr) ? null : Double.parseDouble(priceStr), CurrencyType.valueOf(currencyStr)) - .setContentSchema(TextUtils.isEmpty(contentSchemaStr) ? null : BranchContentSchema.valueOf(contentSchemaStr)) - .addCustomMetadata("Custom_Content_metadata_key1", customMetadataStr); - finish(); - } - - private void setSpinnerAdapter(int arrayId, Spinner spinner, String type) { - spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int i, long l) { - switch (type) { - case "productCategory": - productCategoryStr = spinner.getSelectedItem().toString(); - productCategoryStr = productCategoryStr.replace("&", "&"); - break; - case "productCondition": - conditionStr = spinner.getSelectedItem().toString(); - conditionStr = conditionStr.replace("&", "&"); - break; - case "currencyType": - currencyStr = spinner.getSelectedItem().toString(); - currencyStr = currencyStr.replace("&", "&"); - break; - case "contentSchema": - contentSchemaStr = spinner.getSelectedItem().toString(); - contentSchemaStr = contentSchemaStr.replace("&", "&"); - break; - } - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - - } - }); - ArrayAdapter adapter = ArrayAdapter.createFromResource(this, arrayId, android.R.layout.simple_spinner_item); - adapter.setDropDownViewResource(android.R.layout.simple_spinner_item); - spinner.setAdapter(adapter); - } - - -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/ReadDeepLinkActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/ReadDeepLinkActivity.java deleted file mode 100644 index 7a0f54582..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/ReadDeepLinkActivity.java +++ /dev/null @@ -1,188 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.annotation.SuppressLint; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.TextView; - -import androidx.appcompat.app.AppCompatActivity; - -import org.json.JSONObject; - -import io.branch.referral.Branch; -import io.branch.referral.BranchError; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; -import io.branch.saas.sdk.testbed.views.AdvancedWebView; - -public class ReadDeepLinkActivity extends AppCompatActivity implements AdvancedWebView.Listener { - - private AdvancedWebView mWebView; - private boolean isFromReadDeepLink, isFromNotification, isDataLoaded; - private Uri uri; - private String redirectedUrl, deepLinkUrl, clickType; - private TextView tvRedirectedLink; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_read_deeplink); -// Uri uri = getIntent().getData(); - String url = getIntent().getStringExtra(Constants.ANDROID_URL); - clickType = getIntent().getStringExtra(Constants.TYPE); - Log.e("data-->", "here----" + clickType); - isFromNotification = getIntent().getBooleanExtra(Constants.FORCE_NEW_SESSION, false); - if (!TextUtils.isEmpty(url)) { - uri = Uri.parse(url); - isFromReadDeepLink = false; - } else { - uri = getIntent().getData(); - isFromReadDeepLink = true; - } - deepLinkUrl = uri.toString(); - TextView textView = findViewById(R.id.tv_read_link); - tvRedirectedLink = findViewById(R.id.tv_redirected_link); - Button btSubmit = findViewById(R.id.bt_submit); - mWebView = findViewById(R.id.webview); - mWebView.setAnimationCacheEnabled(false); - - if (!TextUtils.isEmpty(clickType) && clickType.equals(Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK)) { - btSubmit.setVisibility(View.GONE); - } else - btSubmit.setVisibility(View.VISIBLE); - if (uri != null) { - textView.setText(uri.toString()); - mWebView.setListener(this, this); - Log.e("url-->", "-->" + uri.toString()); - mWebView.loadUrl(uri.toString()); - - } - btSubmit.setOnClickListener(view -> { - Intent intent = new Intent(ReadDeepLinkActivity.this, LogDataActivity.class); - if (isFromReadDeepLink) - intent.putExtra(Constants.TYPE, Constants.AFTER_READ_DEEP_LINK); - else - intent.putExtra(Constants.TYPE, Constants.LOG_DATA); - if (isDataLoaded) { - intent.putExtra(Constants.STATUS, Constants.SUCCESS); - } else { - intent.putExtra(Constants.STATUS, Constants.FAIL); - } - startActivity(intent); - finish(); - }); - } - - @Override - protected void onStart() { - super.onStart(); - if (!TextUtils.isEmpty(clickType) && clickType.equals(Constants.BUO_REFERENCE_AND_CREATE_DEP_LINK)) { - return; - } - Common.getInstance().clearLog(); - Branch.InitSessionBuilder initSessionBuilder = Branch.sessionBuilder(this).withCallback(new Branch.BranchReferralInitListener() { - @Override - public void onInitFinished(JSONObject referringParams, BranchError error) { - if (error == null) { - isDataLoaded = true; - Log.i("BRANCH SDK", referringParams.toString()); - } else { - Log.i("BRANCH SDK error", error.getMessage()); - } - } - }).withData(uri);//.init(); - if (isFromNotification) - initSessionBuilder.reInit(); - else - initSessionBuilder.init(); - - if (isFromReadDeepLink) { - isDataLoaded = true; - // latest - JSONObject sessionParams = Branch.getInstance().getLatestReferringParams(); - Log.i("BRANCH SDK session", "sessionParams-->" + sessionParams); - - // first - JSONObject installParams = Branch.getInstance().getFirstReferringParams(); - Log.i("BRANCH SDK install", "installParams-->" + installParams); - } - } - - - @SuppressLint("NewApi") - @Override - protected void onResume() { - super.onResume(); - mWebView.onResume(); - // ... - } - - @SuppressLint("NewApi") - @Override - protected void onPause() { - mWebView.onPause(); - // ... - super.onPause(); - } - - @Override - protected void onDestroy() { - mWebView.onDestroy(); - // ... - super.onDestroy(); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent intent) { - super.onActivityResult(requestCode, resultCode, intent); - mWebView.onActivityResult(requestCode, resultCode, intent); - // ... - } - - @Override - public void onBackPressed() { - if (!mWebView.onBackPressed()) { - return; - } - Intent intent = new Intent(this, MainActivity.class); - startActivity(intent); - finish(); - } - - @Override - public void onPageStarted(String url, Bitmap favicon) { - Log.e("onPageStarted", "-->" + url); - if (!url.equals(deepLinkUrl) && TextUtils.isEmpty(redirectedUrl)) { - tvRedirectedLink.setText(url); - tvRedirectedLink.setVisibility(View.VISIBLE); - this.redirectedUrl = url; - } - } - - @Override - public void onPageFinished(String url) { - Log.e("onPageFinished", "-->" + url); - } - - @Override - public void onPageError(int errorCode, String description, String failingUrl) { - Log.e("onPageError", "-->" + failingUrl); - } - - @Override - public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) { - - } - - @Override - public void onExternalPageRequest(String url) { - Log.e("onExternalPageRequest", "-->" + url); - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/TrackContentActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/TrackContentActivity.java deleted file mode 100644 index 8059659ce..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/TrackContentActivity.java +++ /dev/null @@ -1,61 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.content.Intent; -import android.os.Bundle; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Spinner; - -import androidx.appcompat.app.AppCompatActivity; - -import io.branch.referral.util.BRANCH_STANDARD_EVENT; -import io.branch.saas.sdk.testbed.Common; -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; - -public class TrackContentActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { - - private Spinner trackContentSpinner; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_track_content); - - trackContentSpinner = findViewById(R.id.track_content_spinner); - trackContentSpinner.setOnItemSelectedListener(this); - ArrayAdapter ad - = new ArrayAdapter( - this, - android.R.layout.simple_spinner_item, - getResources().getStringArray(R.array.track_content_items)); - - // set simple layout resource file - // for each item of spinner - ad.setDropDownViewResource( - android.R.layout - .simple_spinner_dropdown_item); - - // Set the ArrayAdapter (ad) data on the - // Spinner which binds data to spinner - trackContentSpinner.setAdapter(ad); - findViewById(R.id.bt_submit).setOnClickListener(view -> { - Intent intent = new Intent(TrackContentActivity.this, BUOReferenceActivity.class); - intent.putExtra(Constants.TYPE, Constants.TRACK_CONTENT); - startActivity(intent); - finish(); - }); - } - - @Override - public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - Common.getInstance().branchStandardEvent = BRANCH_STANDARD_EVENT.valueOf(trackContentSpinner.getSelectedItem().toString()); - - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/UrlPreviewActivity.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/UrlPreviewActivity.java deleted file mode 100644 index 1322630ca..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/activities/UrlPreviewActivity.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.branch.saas.sdk.testbed.activities; - -import android.content.Intent; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.text.method.LinkMovementMethod; -import android.view.MenuItem; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; - -import io.branch.saas.sdk.testbed.Constants; -import io.branch.saas.sdk.testbed.R; - -public class UrlPreviewActivity extends AppCompatActivity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_url_preview); - getSupportActionBar().setTitle("Result URL"); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - TextView tvUrl = findViewById(R.id.tv_url); - String url = getIntent().getStringExtra(Constants.ANDROID_URL); - tvUrl.setText(url); - tvUrl.setMovementMethod(LinkMovementMethod.getInstance()); - findViewById(R.id.bt_read_deep_link).setOnClickListener(view -> { - Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url)); -// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) - intent.setPackage(getPackageName()); - startActivity(intent); - finish(); - }); - } - - // this event will enable the back - // function to the button on press - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - this.finish(); - return true; - } - return super.onOptionsItemSelected(item); - } -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/listeners/DialogClickListener.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/listeners/DialogClickListener.java deleted file mode 100644 index 4481eb544..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/listeners/DialogClickListener.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.branch.saas.sdk.testbed.listeners; - -public interface DialogClickListener { - void onDialogDismissed(); -} diff --git a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/views/AdvancedWebView.java b/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/views/AdvancedWebView.java deleted file mode 100644 index d0e578146..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/java/io/branch/saas/sdk/testbed/views/AdvancedWebView.java +++ /dev/null @@ -1,1422 +0,0 @@ -package io.branch.saas.sdk.testbed.views; -/* - * Android-AdvancedWebView (https://github.com/delight-im/Android-AdvancedWebView) - * Copyright (c) delight.im (https://www.delight.im/) - * Licensed under the MIT License (https://opensource.org/licenses/MIT) - */ - -import android.content.ActivityNotFoundException; -import android.view.ViewGroup; -import android.app.DownloadManager; -import android.app.DownloadManager.Request; -import android.os.Environment; -import android.webkit.CookieManager; -import java.util.Arrays; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import java.util.HashMap; -import android.net.http.SslError; -import android.view.InputEvent; -import android.view.KeyEvent; -import android.webkit.ClientCertRequest; -import android.webkit.HttpAuthHandler; -import android.webkit.SslErrorHandler; -import android.webkit.URLUtil; -import android.webkit.WebResourceRequest; -import android.webkit.WebResourceResponse; -import android.os.Message; -import android.view.View; -import android.webkit.ConsoleMessage; -import android.webkit.GeolocationPermissions.Callback; -import android.webkit.JsPromptResult; -import android.webkit.JsResult; -import android.webkit.PermissionRequest; -import android.webkit.WebStorage.QuotaUpdater; -import android.app.Fragment; -import android.util.Base64; -import android.os.Build; -import android.webkit.DownloadListener; -import android.graphics.Bitmap; -import android.app.Activity; -import android.content.Intent; -import android.net.Uri; -import android.webkit.ValueCallback; -import android.webkit.WebChromeClient; -import android.webkit.WebViewClient; -import android.webkit.WebSettings; -import android.annotation.SuppressLint; -import android.content.Context; -import android.util.AttributeSet; -import android.webkit.WebView; -import java.util.MissingResourceException; -import java.util.Locale; -import java.util.LinkedList; -import java.util.Collection; -import java.util.List; -import java.io.UnsupportedEncodingException; -import java.lang.ref.WeakReference; -import java.util.Map; -import java.util.Objects; - -import io.branch.referral.BranchLogger; - -/** Advanced WebView component for Android that works as intended out of the box */ -public class AdvancedWebView extends WebView { - - public interface Listener { - void onPageStarted(String url, Bitmap favicon); - void onPageFinished(String url); - void onPageError(int errorCode, String description, String failingUrl); - void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent); - void onExternalPageRequest(String url); - } - - public static final String PACKAGE_NAME_DOWNLOAD_MANAGER = "com.android.providers.downloads"; - protected static final int REQUEST_CODE_FILE_PICKER = 51426; - protected static final String DATABASES_SUB_FOLDER = "/databases"; - protected static final String LANGUAGE_DEFAULT_ISO3 = "eng"; - protected static final String CHARSET_DEFAULT = "UTF-8"; - /** Alternative browsers that have their own rendering engine and *may* be installed on this device */ - protected static final String[] ALTERNATIVE_BROWSERS = new String[] { "org.mozilla.firefox", "com.android.chrome", "com.opera.browser", "org.mozilla.firefox_beta", "com.chrome.beta", "com.opera.browser.beta" }; - protected WeakReference mActivity; - protected WeakReference mFragment; - protected Listener mListener; - protected final List mPermittedHostnames = new LinkedList(); - /** File upload callback for platform versions prior to Android 5.0 */ - protected ValueCallback mFileUploadCallbackFirst; - /** File upload callback for Android 5.0+ */ - protected ValueCallback mFileUploadCallbackSecond; - protected long mLastError; - protected String mLanguageIso3; - protected int mRequestCodeFilePicker = REQUEST_CODE_FILE_PICKER; - protected WebViewClient mCustomWebViewClient; - protected WebChromeClient mCustomWebChromeClient; - protected boolean mGeolocationEnabled; - protected String mUploadableFileTypes = "*/*"; - protected final Map mHttpHeaders = new HashMap(); - - public AdvancedWebView(Context context) { - super(context); - init(context); - } - - public AdvancedWebView(Context context, AttributeSet attrs) { - super(context, attrs); - init(context); - } - - public AdvancedWebView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context); - } - - public void setListener(final Activity activity, final Listener listener) { - setListener(activity, listener, REQUEST_CODE_FILE_PICKER); - } - - public void setListener(final Activity activity, final Listener listener, final int requestCodeFilePicker) { - if (activity != null) { - mActivity = new WeakReference(activity); - } - else { - mActivity = null; - } - - setListener(listener, requestCodeFilePicker); - } - - public void setListener(final Fragment fragment, final Listener listener) { - setListener(fragment, listener, REQUEST_CODE_FILE_PICKER); - } - - public void setListener(final Fragment fragment, final Listener listener, final int requestCodeFilePicker) { - if (fragment != null) { - mFragment = new WeakReference(fragment); - } - else { - mFragment = null; - } - - setListener(listener, requestCodeFilePicker); - } - - protected void setListener(final Listener listener, final int requestCodeFilePicker) { - mListener = listener; - mRequestCodeFilePicker = requestCodeFilePicker; - } - - @Override - public void setWebViewClient(final WebViewClient client) { - mCustomWebViewClient = client; - } - - @Override - public void setWebChromeClient(final WebChromeClient client) { - mCustomWebChromeClient = client; - } - - @SuppressLint("SetJavaScriptEnabled") - public void setGeolocationEnabled(final boolean enabled) { - if (enabled) { - getSettings().setJavaScriptEnabled(true); - getSettings().setGeolocationEnabled(true); - setGeolocationDatabasePath(); - } - - mGeolocationEnabled = enabled; - } - - @SuppressLint("NewApi") - protected void setGeolocationDatabasePath() { - final Activity activity; - - if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11 && mFragment.get().getActivity() != null) { - activity = mFragment.get().getActivity(); - } - else if (mActivity != null && mActivity.get() != null) { - activity = mActivity.get(); - } - else { - return; - } - - getSettings().setGeolocationDatabasePath(activity.getFilesDir().getPath()); - } - - public void setUploadableFileTypes(final String mimeType) { - mUploadableFileTypes = mimeType; - } - - /** - * Loads and displays the provided HTML source text - * - * @param html the HTML source text to load - */ - public void loadHtml(final String html) { - loadHtml(html, null); - } - - /** - * Loads and displays the provided HTML source text - * - * @param html the HTML source text to load - * @param baseUrl the URL to use as the page's base URL - */ - public void loadHtml(final String html, final String baseUrl) { - loadHtml(html, baseUrl, null); - } - - /** - * Loads and displays the provided HTML source text - * - * @param html the HTML source text to load - * @param baseUrl the URL to use as the page's base URL - * @param historyUrl the URL to use for the page's history entry - */ - public void loadHtml(final String html, final String baseUrl, final String historyUrl) { - loadHtml(html, baseUrl, historyUrl, "utf-8"); - } - - /** - * Loads and displays the provided HTML source text - * - * @param html the HTML source text to load - * @param baseUrl the URL to use as the page's base URL - * @param historyUrl the URL to use for the page's history entry - * @param encoding the encoding or charset of the HTML source text - */ - public void loadHtml(final String html, final String baseUrl, final String historyUrl, final String encoding) { - loadDataWithBaseURL(baseUrl, html, "text/html", encoding, historyUrl); - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onResume() { - if (Build.VERSION.SDK_INT >= 11) { - super.onResume(); - } - resumeTimers(); - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onPause() { - pauseTimers(); - if (Build.VERSION.SDK_INT >= 11) { - super.onPause(); - } - } - - public void onDestroy() { - // try to remove this view from its parent first - try { - ((ViewGroup) getParent()).removeView(this); - } - catch (Exception e) { - BranchLogger.d(e.getMessage()); - } - - // then try to remove all child views from this view - try { - removeAllViews(); - } - catch (Exception e) { - BranchLogger.d(e.getMessage()); - } - - // and finally destroy this view - destroy(); - } - - public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { - if (requestCode == mRequestCodeFilePicker) { - if (resultCode == Activity.RESULT_OK) { - if (intent != null) { - if (mFileUploadCallbackFirst != null) { - mFileUploadCallbackFirst.onReceiveValue(intent.getData()); - mFileUploadCallbackFirst = null; - } - else if (mFileUploadCallbackSecond != null) { - Uri[] dataUris = null; - - try { - if (intent.getDataString() != null) { - dataUris = new Uri[] { Uri.parse(intent.getDataString()) }; - } - else { - if (Build.VERSION.SDK_INT >= 16) { - if (intent.getClipData() != null) { - final int numSelectedFiles = intent.getClipData().getItemCount(); - - dataUris = new Uri[numSelectedFiles]; - - for (int i = 0; i < numSelectedFiles; i++) { - dataUris[i] = intent.getClipData().getItemAt(i).getUri(); - } - } - } - } - } - catch (Exception e) { - BranchLogger.d(e.getMessage()); - } - - mFileUploadCallbackSecond.onReceiveValue(dataUris); - mFileUploadCallbackSecond = null; - } - } - } - else { - if (mFileUploadCallbackFirst != null) { - mFileUploadCallbackFirst.onReceiveValue(null); - mFileUploadCallbackFirst = null; - } - else if (mFileUploadCallbackSecond != null) { - mFileUploadCallbackSecond.onReceiveValue(null); - mFileUploadCallbackSecond = null; - } - } - } - } - - /** - * Adds an additional HTTP header that will be sent along with every HTTP `GET` request - * - * This does only affect the main requests, not the requests to included resources (e.g. images) - * - * If you later want to delete an HTTP header that was previously added this way, call `removeHttpHeader()` - * - * The `WebView` implementation may in some cases overwrite headers that you set or unset - * - * @param name the name of the HTTP header to add - * @param value the value of the HTTP header to send - */ - public void addHttpHeader(final String name, final String value) { - mHttpHeaders.put(name, value); - } - - /** - * Removes one of the HTTP headers that have previously been added via `addHttpHeader()` - * - * If you want to unset a pre-defined header, set it to an empty string with `addHttpHeader()` instead - * - * The `WebView` implementation may in some cases overwrite headers that you set or unset - * - * @param name the name of the HTTP header to remove - */ - public void removeHttpHeader(final String name) { - mHttpHeaders.remove(name); - } - - public void addPermittedHostname(String hostname) { - mPermittedHostnames.add(hostname); - } - - public void addPermittedHostnames(Collection collection) { - mPermittedHostnames.addAll(collection); - } - - public List getPermittedHostnames() { - return mPermittedHostnames; - } - - public void removePermittedHostname(String hostname) { - mPermittedHostnames.remove(hostname); - } - - public void clearPermittedHostnames() { - mPermittedHostnames.clear(); - } - - public boolean onBackPressed() { - if (canGoBack()) { - goBack(); - return false; - } - else { - return true; - } - } - - @SuppressLint("NewApi") - protected static void setAllowAccessFromFileUrls(final WebSettings webSettings, final boolean allowed) { - if (Build.VERSION.SDK_INT >= 16) { - webSettings.setAllowFileAccessFromFileURLs(allowed); - webSettings.setAllowUniversalAccessFromFileURLs(allowed); - } - } - - @SuppressWarnings("static-method") - public void setCookiesEnabled(final boolean enabled) { - CookieManager.getInstance().setAcceptCookie(enabled); - } - - @SuppressLint("NewApi") - public void setThirdPartyCookiesEnabled(final boolean enabled) { - if (Build.VERSION.SDK_INT >= 21) { - CookieManager.getInstance().setAcceptThirdPartyCookies(this, enabled); - } - } - - public void setMixedContentAllowed(final boolean allowed) { - setMixedContentAllowed(getSettings(), allowed); - } - - @SuppressWarnings("static-method") - @SuppressLint("NewApi") - protected void setMixedContentAllowed(final WebSettings webSettings, final boolean allowed) { - if (Build.VERSION.SDK_INT >= 21) { - webSettings.setMixedContentMode(allowed ? WebSettings.MIXED_CONTENT_ALWAYS_ALLOW : WebSettings.MIXED_CONTENT_NEVER_ALLOW); - } - } - - public void setDesktopMode(final boolean enabled) { - final WebSettings webSettings = getSettings(); - - final String newUserAgent; - if (enabled) { - newUserAgent = webSettings.getUserAgentString().replace("Mobile", "eliboM").replace("Android", "diordnA"); - } - else { - newUserAgent = webSettings.getUserAgentString().replace("eliboM", "Mobile").replace("diordnA", "Android"); - } - - webSettings.setUserAgentString(newUserAgent); - webSettings.setUseWideViewPort(enabled); - webSettings.setLoadWithOverviewMode(enabled); - webSettings.setSupportZoom(enabled); - webSettings.setBuiltInZoomControls(enabled); - } - - @SuppressLint({ "SetJavaScriptEnabled" }) - protected void init(Context context) { - // in IDE's preview mode - if (isInEditMode()) { - // do not run the code from this method - return; - } - - if (context instanceof Activity) { - mActivity = new WeakReference((Activity) context); - } - - mLanguageIso3 = getLanguageIso3(); - - setFocusable(true); - setFocusableInTouchMode(true); - - setSaveEnabled(true); - - final String filesDir = context.getFilesDir().getPath(); - final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER; - - final WebSettings webSettings = getSettings(); - webSettings.setAllowFileAccess(false); - setAllowAccessFromFileUrls(webSettings, false); - webSettings.setBuiltInZoomControls(false); - webSettings.setJavaScriptEnabled(true); - webSettings.setDomStorageEnabled(true); - if (Build.VERSION.SDK_INT < 18) { - webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); - } - webSettings.setDatabaseEnabled(true); - if (Build.VERSION.SDK_INT < 19) { - webSettings.setDatabasePath(databaseDir); - } - - if (Build.VERSION.SDK_INT >= 21) { - webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE); - } - - setThirdPartyCookiesEnabled(true); - - super.setWebViewClient(new WebViewClient() { - - @Override - public void onPageStarted(WebView view, String url, Bitmap favicon) { - if (!hasError()) { - if (mListener != null) { - mListener.onPageStarted(url, favicon); - } - } - - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onPageStarted(view, url, favicon); - } - } - - @Override - public void onPageFinished(WebView view, String url) { - if (!hasError()) { - if (mListener != null) { - mListener.onPageFinished(url); - } - } - - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onPageFinished(view, url); - } - } - - @Override - public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { - setLastError(); - - if (mListener != null) { - mListener.onPageError(errorCode, description, failingUrl); - } - - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl); - } - } - - @Override - public boolean shouldOverrideUrlLoading(final WebView view, final String url) { - if (!isPermittedUrl(url)) { - // if a listener is available - if (mListener != null) { - // inform the listener about the request - mListener.onExternalPageRequest(url); - } - - // cancel the original request - return true; - } - - // if there is a user-specified handler available - if (mCustomWebViewClient != null) { - // if the user-specified handler asks to override the request - if (mCustomWebViewClient.shouldOverrideUrlLoading(view, url)) { - // cancel the original request - return true; - } - } - - final Uri uri = Uri.parse(url); - final String scheme = uri.getScheme(); - - if (scheme != null) { - final Intent externalSchemeIntent; - - if (scheme.equals("tel")) { - externalSchemeIntent = new Intent(Intent.ACTION_DIAL, uri); - } - else if (scheme.equals("sms")) { - externalSchemeIntent = new Intent(Intent.ACTION_SENDTO, uri); - } - else if (scheme.equals("mailto")) { - externalSchemeIntent = new Intent(Intent.ACTION_SENDTO, uri); - } - else if (scheme.equals("whatsapp")) { - externalSchemeIntent = new Intent(Intent.ACTION_SENDTO, uri); - externalSchemeIntent.setPackage("com.whatsapp"); - } - else { - externalSchemeIntent = null; - } - - if (externalSchemeIntent != null) { - externalSchemeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - - try { - if (mActivity != null && mActivity.get() != null) { - mActivity.get().startActivity(externalSchemeIntent); - } - else { - getContext().startActivity(externalSchemeIntent); - } - } - catch (ActivityNotFoundException e) { - BranchLogger.d(e.getMessage()); - } - - // cancel the original request - return true; - } - } - - // route the request through the custom URL loading method - view.loadUrl(url); - - // cancel the original request - return true; - } - - @Override - public void onLoadResource(WebView view, String url) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onLoadResource(view, url); - } - else { - super.onLoadResource(view, url); - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public WebResourceResponse shouldInterceptRequest(WebView view, String url) { - if (Build.VERSION.SDK_INT >= 11) { - if (mCustomWebViewClient != null) { - return mCustomWebViewClient.shouldInterceptRequest(view, url); - } - else { - return super.shouldInterceptRequest(view, url); - } - } - else { - return null; - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { - if (Build.VERSION.SDK_INT >= 21) { - if (mCustomWebViewClient != null) { - return mCustomWebViewClient.shouldInterceptRequest(view, request); - } - else { - return super.shouldInterceptRequest(view, request); - } - } - else { - return null; - } - } - - @Override - public void onFormResubmission(WebView view, Message dontResend, Message resend) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onFormResubmission(view, dontResend, resend); - } - else { - super.onFormResubmission(view, dontResend, resend); - } - } - - @Override - public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload); - } - else { - super.doUpdateVisitedHistory(view, url, isReload); - } - } - - @Override - public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onReceivedSslError(view, handler, error); - } - else { - super.onReceivedSslError(view, handler, error); - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { - if (Build.VERSION.SDK_INT >= 21) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onReceivedClientCertRequest(view, request); - } - else { - super.onReceivedClientCertRequest(view, request); - } - } - } - - @Override - public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); - } - else { - super.onReceivedHttpAuthRequest(view, handler, host, realm); - } - } - - @Override - public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { - if (mCustomWebViewClient != null) { - return mCustomWebViewClient.shouldOverrideKeyEvent(view, event); - } - else { - return super.shouldOverrideKeyEvent(view, event); - } - } - - @Override - public void onUnhandledKeyEvent(WebView view, KeyEvent event) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onUnhandledKeyEvent(view, event); - } - else { - super.onUnhandledKeyEvent(view, event); - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onUnhandledInputEvent(WebView view, InputEvent event) { - - } - - @Override - public void onScaleChanged(WebView view, float oldScale, float newScale) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onScaleChanged(view, oldScale, newScale); - } - else { - super.onScaleChanged(view, oldScale, newScale); - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { - if (Build.VERSION.SDK_INT >= 12) { - if (mCustomWebViewClient != null) { - mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args); - } - else { - super.onReceivedLoginRequest(view, realm, account, args); - } - } - } - - }); - - super.setWebChromeClient(new WebChromeClient() { - - // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method) - @SuppressWarnings("unused") - public void openFileChooser(ValueCallback uploadMsg) { - openFileChooser(uploadMsg, null); - } - - // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method) - public void openFileChooser(ValueCallback uploadMsg, String acceptType) { - openFileChooser(uploadMsg, acceptType, null); - } - - // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method) - @SuppressWarnings("unused") - public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) { - openFileInput(uploadMsg, null, false); - } - - // file upload callback (Android 5.0 (API level 21) -- current) (public method) - @SuppressWarnings("all") - public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { - if (Build.VERSION.SDK_INT >= 21) { - final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE; - - openFileInput(null, filePathCallback, allowMultiple); - - return true; - } - else { - return false; - } - } - - @Override - public void onProgressChanged(WebView view, int newProgress) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onProgressChanged(view, newProgress); - } - else { - super.onProgressChanged(view, newProgress); - } - } - - @Override - public void onReceivedTitle(WebView view, String title) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onReceivedTitle(view, title); - } - else { - super.onReceivedTitle(view, title); - } - } - - @Override - public void onReceivedIcon(WebView view, Bitmap icon) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onReceivedIcon(view, icon); - } - else { - super.onReceivedIcon(view, icon); - } - } - - @Override - public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed); - } - else { - super.onReceivedTouchIconUrl(view, url, precomposed); - } - } - - @Override - public void onShowCustomView(View view, CustomViewCallback callback) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onShowCustomView(view, callback); - } - else { - super.onShowCustomView(view, callback); - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { - if (Build.VERSION.SDK_INT >= 14) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback); - } - else { - super.onShowCustomView(view, requestedOrientation, callback); - } - } - } - - @Override - public void onHideCustomView() { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onHideCustomView(); - } - else { - super.onHideCustomView(); - } - } - - @Override - public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg); - } - else { - return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); - } - } - - @Override - public void onRequestFocus(WebView view) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onRequestFocus(view); - } - else { - super.onRequestFocus(view); - } - } - - @Override - public void onCloseWindow(WebView window) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onCloseWindow(window); - } - else { - super.onCloseWindow(window); - } - } - - @Override - public boolean onJsAlert(WebView view, String url, String message, JsResult result) { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onJsAlert(view, url, message, result); - } - else { - return super.onJsAlert(view, url, message, result); - } - } - - @Override - public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onJsConfirm(view, url, message, result); - } - else { - return super.onJsConfirm(view, url, message, result); - } - } - - @Override - public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result); - } - else { - return super.onJsPrompt(view, url, message, defaultValue, result); - } - } - - @Override - public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result); - } - else { - return super.onJsBeforeUnload(view, url, message, result); - } - } - - @Override - public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { - if (mGeolocationEnabled) { - callback.invoke(origin, true, false); - } - else { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback); - } - else { - super.onGeolocationPermissionsShowPrompt(origin, callback); - } - } - } - - @Override - public void onGeolocationPermissionsHidePrompt() { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onGeolocationPermissionsHidePrompt(); - } - else { - super.onGeolocationPermissionsHidePrompt(); - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onPermissionRequest(PermissionRequest request) { - if (Build.VERSION.SDK_INT >= 21) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onPermissionRequest(request); - } - else { - super.onPermissionRequest(request); - } - } - } - - @SuppressLint("NewApi") - @SuppressWarnings("all") - public void onPermissionRequestCanceled(PermissionRequest request) { - if (Build.VERSION.SDK_INT >= 21) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onPermissionRequestCanceled(request); - } - else { - super.onPermissionRequestCanceled(request); - } - } - } - - @Override - public boolean onJsTimeout() { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onJsTimeout(); - } - else { - return super.onJsTimeout(); - } - } - - @Override - public void onConsoleMessage(String message, int lineNumber, String sourceID) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID); - } - else { - super.onConsoleMessage(message, lineNumber, sourceID); - } - } - - @Override - public boolean onConsoleMessage(ConsoleMessage consoleMessage) { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.onConsoleMessage(consoleMessage); - } - else { - return super.onConsoleMessage(consoleMessage); - } - } - - @Override - public Bitmap getDefaultVideoPoster() { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.getDefaultVideoPoster(); - } - else { - return super.getDefaultVideoPoster(); - } - } - - @Override - public View getVideoLoadingProgressView() { - if (mCustomWebChromeClient != null) { - return mCustomWebChromeClient.getVideoLoadingProgressView(); - } - else { - return super.getVideoLoadingProgressView(); - } - } - - @Override - public void getVisitedHistory(ValueCallback callback) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.getVisitedHistory(callback); - } - else { - super.getVisitedHistory(callback); - } - } - - @Override - public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { - if (mCustomWebChromeClient != null) { - mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); - } - else { - super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); - } - } - }); - - setDownloadListener(new DownloadListener() { - - @Override - public void onDownloadStart(final String url, final String userAgent, final String contentDisposition, final String mimeType, final long contentLength) { - final String suggestedFilename = URLUtil.guessFileName(url, contentDisposition, mimeType); - - if (mListener != null) { - mListener.onDownloadRequested(url, suggestedFilename, mimeType, contentLength, contentDisposition, userAgent); - } - } - - }); - } - - @Override - public void loadUrl(final String url, Map additionalHttpHeaders) { - if (additionalHttpHeaders == null) { - additionalHttpHeaders = mHttpHeaders; - } - else if (mHttpHeaders.size() > 0) { - additionalHttpHeaders.putAll(mHttpHeaders); - } - - super.loadUrl(url, additionalHttpHeaders); - } - - @Override - public void loadUrl(final String url) { - if (mHttpHeaders.size() > 0) { - super.loadUrl(url, mHttpHeaders); - } - else { - super.loadUrl(url); - } - } - - public void loadUrl(String url, final boolean preventCaching) { - if (preventCaching) { - url = makeUrlUnique(url); - } - - loadUrl(url); - } - - public void loadUrl(String url, final boolean preventCaching, final Map additionalHttpHeaders) { - if (preventCaching) { - url = makeUrlUnique(url); - } - - loadUrl(url, additionalHttpHeaders); - } - - protected static String makeUrlUnique(final String url) { - StringBuilder unique = new StringBuilder(); - unique.append(url); - - if (url.contains("?")) { - unique.append('&'); - } - else { - if (url.lastIndexOf('/') <= 7) { - unique.append('/'); - } - unique.append('?'); - } - - unique.append(System.currentTimeMillis()); - unique.append('='); - unique.append(1); - - return unique.toString(); - } - - public boolean isPermittedUrl(final String url) { - // if the permitted hostnames have not been restricted to a specific set - if (mPermittedHostnames.size() == 0) { - // all hostnames are allowed - return true; - } - - final Uri parsedUrl = Uri.parse(url); - - // get the hostname of the URL that is to be checked - final String actualHost = parsedUrl.getHost(); - - // if the hostname could not be determined, usually because the URL has been invalid - if (actualHost == null) { - return false; - } - - // if the host contains invalid characters (e.g. a backslash) - if (!actualHost.matches("^[a-zA-Z0-9._!~*')(;:&=+$,%\\[\\]-]*$")) { - // prevent mismatches between interpretations by `Uri` and `WebView`, e.g. for `http://evil.example.com\.good.example.com/` - return false; - } - - // get the user information from the authority part of the URL that is to be checked - final String actualUserInformation = parsedUrl.getUserInfo(); - - // if the user information contains invalid characters (e.g. a backslash) - if (actualUserInformation != null && !actualUserInformation.matches("^[a-zA-Z0-9._!~*')(;:&=+$,%-]*$")) { - // prevent mismatches between interpretations by `Uri` and `WebView`, e.g. for `http://evil.example.com\@good.example.com/` - return false; - } - - // for every hostname in the set of permitted hosts - for (String expectedHost : mPermittedHostnames) { - // if the two hostnames match or if the actual host is a subdomain of the expected host - if (actualHost.equals(expectedHost) || actualHost.endsWith("." + expectedHost)) { - // the actual hostname of the URL to be checked is allowed - return true; - } - } - - // the actual hostname of the URL to be checked is not allowed since there were no matches - return false; - } - - /** - * @deprecated use `isPermittedUrl` instead - */ - protected boolean isHostnameAllowed(final String url) { - return isPermittedUrl(url); - } - - protected void setLastError() { - mLastError = System.currentTimeMillis(); - } - - protected boolean hasError() { - return (mLastError + 500) >= System.currentTimeMillis(); - } - - protected static String getLanguageIso3() { - try { - return Locale.getDefault().getISO3Language().toLowerCase(Locale.US); - } - catch (MissingResourceException e) { - return LANGUAGE_DEFAULT_ISO3; - } - } - - /** - * Provides localizations for the 25 most widely spoken languages that have a ISO 639-2/T code - * - * @return the label for the file upload prompts as a string - */ - protected String getFileUploadPromptLabel() { - try { - if (mLanguageIso3.equals("zho")) return decodeBase64("6YCJ5oup5LiA5Liq5paH5Lu2"); - else if (mLanguageIso3.equals("spa")) return decodeBase64("RWxpamEgdW4gYXJjaGl2bw=="); - else if (mLanguageIso3.equals("hin")) return decodeBase64("4KSP4KSVIOCkq+CkvOCkvuCkh+CksiDgpJrgpYHgpKjgpYfgpII="); - else if (mLanguageIso3.equals("ben")) return decodeBase64("4KaP4KaV4Kaf4Ka/IOCmq+CmvuCmh+CmsiDgpqjgpr/gprDgp43gpqzgpr7gpprgpqg="); - else if (mLanguageIso3.equals("ara")) return decodeBase64("2KfYrtiq2YrYp9ixINmF2YTZgSDZiNin2K3Yrw=="); - else if (mLanguageIso3.equals("por")) return decodeBase64("RXNjb2xoYSB1bSBhcnF1aXZv"); - else if (mLanguageIso3.equals("rus")) return decodeBase64("0JLRi9Cx0LXRgNC40YLQtSDQvtC00LjQvSDRhNCw0LnQuw=="); - else if (mLanguageIso3.equals("jpn")) return decodeBase64("MeODleOCoeOCpOODq+OCkumBuOaKnuOBl+OBpuOBj+OBoOOBleOBhA=="); - else if (mLanguageIso3.equals("pan")) return decodeBase64("4KiH4Kmx4KiVIOCoq+CovuCoh+CosiDgqJrgqYHgqKPgqYs="); - else if (mLanguageIso3.equals("deu")) return decodeBase64("V8OkaGxlIGVpbmUgRGF0ZWk="); - else if (mLanguageIso3.equals("jav")) return decodeBase64("UGlsaWggc2lqaSBiZXJrYXM="); - else if (mLanguageIso3.equals("msa")) return decodeBase64("UGlsaWggc2F0dSBmYWls"); - else if (mLanguageIso3.equals("tel")) return decodeBase64("4LCS4LCVIOCwq+CxhuCxluCwsuCxjeCwqOCxgSDgsI7gsILgsJrgsYHgsJXgsYvgsILgsKHgsL8="); - else if (mLanguageIso3.equals("vie")) return decodeBase64("Q2jhu41uIG3hu5l0IHThuq1wIHRpbg=="); - else if (mLanguageIso3.equals("kor")) return decodeBase64("7ZWY64KY7J2YIO2MjOydvOydhCDshKDtg50="); - else if (mLanguageIso3.equals("fra")) return decodeBase64("Q2hvaXNpc3NleiB1biBmaWNoaWVy"); - else if (mLanguageIso3.equals("mar")) return decodeBase64("4KSr4KS+4KSH4KSyIOCkqOCkv+CkteCkoeCkvg=="); - else if (mLanguageIso3.equals("tam")) return decodeBase64("4K6S4K6w4K+BIOCuleCvh+CuvuCuquCvjeCuquCviCDgrqTgr4fgrrDgr43grrXgr4E="); - else if (mLanguageIso3.equals("urd")) return decodeBase64("2KfbjNqpINmB2KfYptmEINmF24zauiDYs9uSINin2YbYqtiu2KfYqCDaqdix24zaug=="); - else if (mLanguageIso3.equals("fas")) return decodeBase64("2LHYpyDYp9mG2KrYrtin2Kgg2qnZhtuM2K8g24zaqSDZgdin24zZhA=="); - else if (mLanguageIso3.equals("tur")) return decodeBase64("QmlyIGRvc3lhIHNlw6dpbg=="); - else if (mLanguageIso3.equals("ita")) return decodeBase64("U2NlZ2xpIHVuIGZpbGU="); - else if (mLanguageIso3.equals("tha")) return decodeBase64("4LmA4Lil4Li34Lit4LiB4LmE4Lif4Lil4LmM4Lir4LiZ4Li24LmI4LiH"); - else if (mLanguageIso3.equals("guj")) return decodeBase64("4KqP4KqVIOCqq+CqvuCqh+CqsuCqqOCrhyDgqqrgqrjgqoLgqqY="); - } - catch (Exception e) { - BranchLogger.d(e.getMessage()); - } - - // return English translation by default - return "Choose a file"; - } - - protected static String decodeBase64(final String base64) throws IllegalArgumentException, UnsupportedEncodingException { - final byte[] bytes = Base64.decode(base64, Base64.DEFAULT); - return new String(bytes, CHARSET_DEFAULT); - } - - @SuppressLint("NewApi") - protected void openFileInput(final ValueCallback fileUploadCallbackFirst, final ValueCallback fileUploadCallbackSecond, final boolean allowMultiple) { - if (mFileUploadCallbackFirst != null) { - mFileUploadCallbackFirst.onReceiveValue(null); - } - mFileUploadCallbackFirst = fileUploadCallbackFirst; - - if (mFileUploadCallbackSecond != null) { - mFileUploadCallbackSecond.onReceiveValue(null); - } - mFileUploadCallbackSecond = fileUploadCallbackSecond; - - Intent i = new Intent(Intent.ACTION_GET_CONTENT); - i.addCategory(Intent.CATEGORY_OPENABLE); - - if (allowMultiple) { - if (Build.VERSION.SDK_INT >= 18) { - i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); - } - } - - i.setType(mUploadableFileTypes); - - if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11) { - mFragment.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker); - } - else if (mActivity != null && mActivity.get() != null) { - mActivity.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker); - } - } - - /** - * Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) - * - * @return whether file uploads can be used - */ - public static boolean isFileUploadAvailable() { - return isFileUploadAvailable(false); - } - - /** - * Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) - * - * On Android 4.4.3/4.4.4, file uploads may be possible but will come with a wrong MIME type - * - * @param needsCorrectMimeType whether a correct MIME type is required for file uploads or `application/octet-stream` is acceptable - * @return whether file uploads can be used - */ - public static boolean isFileUploadAvailable(final boolean needsCorrectMimeType) { - if (Build.VERSION.SDK_INT == 19) { - final String platformVersion = (Build.VERSION.RELEASE == null) ? "" : Build.VERSION.RELEASE; - - return !needsCorrectMimeType && (platformVersion.startsWith("4.4.3") || platformVersion.startsWith("4.4.4")); - } - else { - return true; - } - } - - /** - * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage - * - * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE` - * - * Only supported on API level 9 (Android 2.3) and above - * - * @param context a valid `Context` reference - * @param fromUrl the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)` - * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg` - * @return whether the download has been successfully handled or not - * @throws IllegalStateException if the storage or the target directory could not be found or accessed - */ - @SuppressLint("NewApi") - public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) { - if (Build.VERSION.SDK_INT < 9) { - throw new RuntimeException("Method requires API level 9 or above"); - } - - final Request request = new Request(Uri.parse(fromUrl)); - if (Build.VERSION.SDK_INT >= 11) { - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - } - request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename); - - final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); - try { - try { - dm.enqueue(request); - } - catch (SecurityException e) { - if (Build.VERSION.SDK_INT >= 11) { - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); - } - dm.enqueue(request); - } - - return true; - } - // if the download manager app has been disabled on the device - catch (IllegalArgumentException e) { - // show the settings screen where the user can enable the download manager app again - openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER); - - return false; - } - } - - @SuppressLint("NewApi") - private static boolean openAppSettings(final Context context, final String packageName) { - if (Build.VERSION.SDK_INT < 9) { - throw new RuntimeException("Method requires API level 9 or above"); - } - - try { - final Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - intent.setData(Uri.parse("package:" + packageName)); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - - context.startActivity(intent); - - return true; - } - catch (Exception e) { - return false; - } - } - - /** Wrapper for methods related to alternative browsers that have their own rendering engines */ - public static class Browsers { - - /** Package name of an alternative browser that is installed on this device */ - private static String mAlternativePackage; - - /** - * Returns whether there is an alternative browser with its own rendering engine currently installed - * - * @param context a valid `Context` reference - * @return whether there is an alternative browser or not - */ - public static boolean hasAlternative(final Context context) { - return getAlternative(context) != null; - } - - /** - * Returns the package name of an alternative browser with its own rendering engine or `null` - * - * @param context a valid `Context` reference - * @return the package name or `null` - */ - public static String getAlternative(final Context context) { - if (mAlternativePackage != null) { - return mAlternativePackage; - } - - final List alternativeBrowsers = Arrays.asList(ALTERNATIVE_BROWSERS); - final List apps = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); - - for (ApplicationInfo app : apps) { - if (!app.enabled) { - continue; - } - - if (alternativeBrowsers.contains(app.packageName)) { - mAlternativePackage = app.packageName; - - return app.packageName; - } - } - - return null; - } - - /** - * Opens the given URL in an alternative browser - * - * @param context a valid `Activity` reference - * @param url the URL to open - */ - public static void openUrl(final Activity context, final String url) { - openUrl(context, url, false); - } - - /** - * Opens the given URL in an alternative browser - * - * @param context a valid `Activity` reference - * @param url the URL to open - * @param withoutTransition whether to switch to the browser `Activity` without a transition - */ - public static void openUrl(final Activity context, final String url, final boolean withoutTransition) { - final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - intent.setPackage(getAlternative(context)); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - - context.startActivity(intent); - - if (withoutTransition) { - context.overridePendingTransition(0, 0); - } - } - - } - -} \ No newline at end of file diff --git a/Branch-SDK-Automation-TestBed/src/main/res/layout/activity_buoreference.xml b/Branch-SDK-Automation-TestBed/src/main/res/layout/activity_buoreference.xml deleted file mode 100644 index 6758adaed..000000000 --- a/Branch-SDK-Automation-TestBed/src/main/res/layout/activity_buoreference.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - -