Skip to content

Commit 48008c7

Browse files
committed
refactor: remove AsyncTask usage for direct network calls and enhance thread safety
- Eliminate BranchAsyncTask and related asynchronous task implementations across multiple classes - Replace AsyncTask calls with direct network calls to improve thread safety and simplify code - Update comments to reflect the modernized approach to handling network requests - This change is part of the ongoing effort to streamline the Branch SDK and enhance performance
1 parent f69fed6 commit 48008c7

File tree

7 files changed

+73
-363
lines changed

7 files changed

+73
-363
lines changed

Branch-SDK-TestBed/src/androidTest/java/io/branch/branchandroidtestbed/BUOTestRoutines.java

Lines changed: 28 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import javax.net.ssl.HttpsURLConnection;
1919

2020
import io.branch.indexing.BranchUniversalObject;
21-
import io.branch.referral.BranchAsyncTask;
2221
import io.branch.referral.BranchLogger;
2322
import io.branch.referral.BranchUtil;
2423
import io.branch.referral.util.BranchContentSchema;
@@ -102,18 +101,41 @@ private static boolean doLinkCreationTest(Context context, BranchUniversalObject
102101
boolean isLinkTestPassed = false;
103102
String url = buo.getShortUrl(context, new LinkProperties());
104103
try {
105-
JSONObject linkdata = new URLContentViewer().execute(url, BranchUtil.readBranchKey(context)).get();
104+
// Direct network call instead of AsyncTask for thread safety
105+
JSONObject linkdata = fetchURLContent(url, BranchUtil.readBranchKey(context));
106106
isLinkTestPassed = checkIfIdenticalJson(buo.convertToJson(), linkdata.optJSONObject("data"), true);
107107
if (isLinkTestPassed) {
108108
isLinkTestPassed = checkIfIdenticalJson(BranchUniversalObject.createInstance(linkdata).convertToJson(), linkdata.optJSONObject("data"), true);
109109
}
110-
} catch (InterruptedException e) {
111-
e.printStackTrace();
112-
} catch (ExecutionException e) {
110+
} catch (Exception e) {
113111
e.printStackTrace();
114112
}
115113
return isLinkTestPassed;
116-
114+
}
115+
116+
private static JSONObject fetchURLContent(String url, String branchKey) {
117+
HttpsURLConnection connection = null;
118+
JSONObject respObject = new JSONObject();
119+
try {
120+
URL urlObject = new URL("https://api.branch.io/v1/url?url=" + url + "&" + "branch_key=" + branchKey);
121+
connection = (HttpsURLConnection) urlObject.openConnection();
122+
connection.setConnectTimeout(1500);
123+
connection.setReadTimeout(1500);
124+
int responseCode = connection.getResponseCode();
125+
if (responseCode == HttpsURLConnection.HTTP_OK) {
126+
if (connection.getInputStream() != null) {
127+
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
128+
respObject = new JSONObject(rd.readLine());
129+
}
130+
}
131+
} catch (Exception e) {
132+
BranchLogger.d(e.getMessage());
133+
} finally {
134+
if (connection != null) {
135+
connection.disconnect();
136+
}
137+
}
138+
return respObject;
117139
}
118140

119141
private static boolean checkIfIdenticalJson(JSONObject obj1, JSONObject obj2, boolean expectBranchExtras) {
@@ -161,34 +183,4 @@ private static boolean checkIfIdenticalJson(JSONObject obj1, JSONObject obj2, bo
161183
return isIdentical;
162184
}
163185

164-
private static class URLContentViewer extends BranchAsyncTask<String, Void, JSONObject> {
165-
166-
@Override
167-
protected JSONObject doInBackground(String... strings) {
168-
HttpsURLConnection connection = null;
169-
JSONObject respObject = new JSONObject();
170-
try {
171-
URL urlObject = new URL("https://api.branch.io/v1/url?url=" + strings[0] + "&" + "branch_key=" + strings[1]);
172-
connection = (HttpsURLConnection) urlObject.openConnection();
173-
connection.setConnectTimeout(1500);
174-
connection.setReadTimeout(1500);
175-
int responseCode = connection.getResponseCode();
176-
if (responseCode == HttpsURLConnection.HTTP_OK) {
177-
if (connection.getInputStream() != null) {
178-
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
179-
respObject = new JSONObject(rd.readLine());
180-
}
181-
}
182-
} catch (Exception e) {
183-
BranchLogger.d(e.getMessage());
184-
} finally {
185-
if (connection != null) {
186-
connection.disconnect();
187-
}
188-
}
189-
190-
return respObject;
191-
}
192-
}
193-
194186
}

Branch-SDK/src/main/java/io/branch/referral/Branch.java

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import android.content.pm.PackageInfo;
2121
import android.content.pm.PackageManager;
2222
import android.net.Uri;
23-
import android.os.AsyncTask;
2423
import android.os.Build;
2524
import android.os.Bundle;
2625
import android.os.Handler;
@@ -240,7 +239,6 @@ public class Branch {
240239
private CustomTabsIntent customTabsIntentOverride;
241240

242241
// Replace SESSION_STATE enum with SessionState
243-
// Legacy session state lock - kept for backward compatibility
244242
private final Object sessionStateLock = new Object();
245243

246244
/* Holds the current intent state. Default is set to PENDING. */
@@ -836,8 +834,6 @@ void unlockSDKInitWaitLock() {
836834
if (requestQueue_ == null) return;
837835
requestQueue_.postInitClear();
838836
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.SDK_INIT_WAIT_LOCK);
839-
// processNextQueueItem call removed - critical SDK initialization unlock handled automatically
840-
// Modern queue processes immediately when SDK_INIT_WAIT_LOCK is released via unlockProcessWait
841837
}
842838

843839
private boolean isIntentParamsAlreadyConsumed(Activity activity) {
@@ -1141,9 +1137,12 @@ private String generateShortLinkSync(ServerRequestCreateUrl req) {
11411137
ServerResponse response = null;
11421138
try {
11431139
int timeOut = prefHelper_.getTimeout() + 2000; // Time out is set to slightly more than link creation time to prevent any edge case
1144-
response = new GetShortLinkTask().execute(req).get(timeOut, TimeUnit.MILLISECONDS);
1145-
} catch (InterruptedException | ExecutionException | TimeoutException e) {
1146-
BranchLogger.d(e.getMessage());
1140+
// Direct network call instead of AsyncTask for thread safety
1141+
response = branchRemoteInterface_.make_restful_post(req.getPost(),
1142+
prefHelper_.getAPIBaseUrl() + Defines.RequestPath.GetURL.getPath(),
1143+
Defines.RequestPath.GetURL.getPath(), prefHelper_.getBranchKey());
1144+
} catch (Exception e) {
1145+
BranchLogger.d("Error generating short link: " + e.getMessage());
11471146
}
11481147
String url = null;
11491148
if (req.isDefaultToLongUrl()) {
@@ -1307,8 +1306,7 @@ void registerAppInit(@NonNull ServerRequestInitSession request, boolean forceBra
13071306
requestQueue_.printQueue();
13081307
initTasks(request);
13091308

1310-
// processNextQueueItem call removed - app initialization processing handled automatically
1311-
// Modern queue processes init session request immediately after initTasks completes
1309+
13121310
}
13131311

13141312
private void initTasks(ServerRequest request) {
@@ -1340,8 +1338,7 @@ public void onInstallReferrersFinished() {
13401338
deviceInfo_.getSystemObserver().fetchAdId(context_, new SystemObserver.AdsParamsFetchEvents() {
13411339
@Override
13421340
public void onAdsParamsFetchFinished() {
1343-
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK);
1344-
// processNextQueueItem call removed - modern queue processes automatically via unlockProcessWait
1341+
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK);
13451342
}
13461343
});
13471344
}
@@ -1369,7 +1366,6 @@ void onIntentReady(@NonNull Activity activity) {
13691366
Uri intentData = activity.getIntent().getData();
13701367
readAndStripParam(intentData, activity);
13711368
}
1372-
// processNextQueueItem call removed - modern queue processes automatically without manual trigger
13731369
}
13741370

13751371
/**
@@ -1515,16 +1511,7 @@ public interface BranchLinkCreateListener {
15151511
*/
15161512

15171513

1518-
/**
1519-
* Async Task to create a short link for synchronous methods
1520-
*/
1521-
private class GetShortLinkTask extends AsyncTask<ServerRequest, Void, ServerResponse> {
1522-
@Override protected ServerResponse doInBackground(ServerRequest... serverRequests) {
1523-
return branchRemoteInterface_.make_restful_post(serverRequests[0].getPost(),
1524-
prefHelper_.getAPIBaseUrl() + Defines.RequestPath.GetURL.getPath(),
1525-
Defines.RequestPath.GetURL.getPath(), prefHelper_.getBranchKey());
1526-
}
1527-
}
1514+
// GetShortLinkTask AsyncTask removed for thread safety - replaced with direct network calls
15281515

15291516
//-------------------Auto deep link feature-------------------------------------------//
15301517

Branch-SDK/src/main/java/io/branch/referral/BranchAsyncTask.java

Lines changed: 0 additions & 27 deletions
This file was deleted.

Branch-SDK/src/main/java/io/branch/referral/DeviceInfo.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,6 @@ private void setPostUserAgent(final JSONObject userDataObj) {
250250
userDataObj.put(Defines.Jsonkey.UserAgent.getKey(), Branch._userAgentString);
251251

252252
Branch.getInstance().requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.USER_AGENT_STRING_LOCK);
253-
// Modern queue processes automatically after unlock - no manual trigger needed
254253
}
255254
else if (Branch.userAgentSync) {
256255
// If user agent sync is false, then the async coroutine is executed instead but may not have finished yet.
@@ -277,7 +276,6 @@ public void resumeWith(@NonNull Object o) {
277276
}
278277

279278
Branch.getInstance().requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.USER_AGENT_STRING_LOCK);
280-
// Modern queue processes automatically after unlock - no manual trigger needed
281279
}
282280
});
283281
}
@@ -305,15 +303,13 @@ public void resumeWith(@NonNull Object o) {
305303
}
306304

307305
Branch.getInstance().requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.USER_AGENT_STRING_LOCK);
308-
// Modern queue processes automatically after unlock - no manual trigger needed
309306
}
310307
});
311308
}
312309
}
313310
catch (Exception exception){
314311
BranchLogger.w("Caught exception trying to set userAgent " + exception.getMessage());
315312
Branch.getInstance().requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.USER_AGENT_STRING_LOCK);
316-
// Modern queue processes automatically after unlock - no manual trigger needed
317313
}
318314
}
319315

0 commit comments

Comments
 (0)