How to make my Android app quickly… here is a solution to the problem.
How to make my Android app quickly
In my android app I use 5 APIs in a class, calling them one by one in onCreate, but this makes my app slower, how to optimize my code to make it faster.
My code looks like this.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
API1();
API2();
API3();
API4();
API5();
}
all the Apis are call in onCreate
public void API1() {
FetchData fetch = new FetchData(this);
fetch.response = new FetchListener() {
@Override
public void fetchFinish(String output) {
try {
JSONObject jobjOUT = new JSONObject(output);
JSONArray jsarray = jobjOUT.getJSONArray("details");
for (int i = 0; i < jsarray.length(); i++) {
JSONObject obj = jsarray.getJSONObject(i);
String a = obj.getString("abc");
}
} catch (Exception e) {
TODO Auto-generated catch block
e.printStackTrace();
}
}
};
try {
fetch.execute("http://example.com/api/something.php?param=xyz");
} catch (Exception e) {
TODO Auto-generated catch block
e.printStackTrace();
}
}
public void API2() {
same code here
}
public void API3() {
same code here
}
public void API4() {
same code here
}
public void API5() {
same code here
}
}
My question is can I call all the APIs at the same time instead of calling them one by one? Please give me some suggestions to optimize my code.
Thank you
Solution
Try using a thread pool executor
Quotethis sum this to learn and understand. By using thread pool executors
, you can run several tasks at the same time, or we can say parallel.
private void startAsyncTaskInParallel(MyAsyncTask task) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES. HONEYCOMB)
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
task.execute();
}