Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start new Android Activity is so slow

I want to open a new Activity:

Intent intent = new Intent(homeScreen.this, EmployeeService.class);         
Bundle b = new Bundle();
b.putInt(Constants.SERVICE_DETAIL_L1_ID_MSG, ServiceIndex.SRV_L1_EMPLOYMENT);
b.putInt(Constants.SERVICE_DETAIL_FOCUS_POS_MSG, 2);
intent.putExtras(b);
startActivity(intent);

But it takes so long to make destination Activity (EmployeeService) become visible. From Logcat, I see:

05-14 23:43:31.727: INFO/ActivityManager(59): Displayed activity fr.playsoft.happylille/.employee.EmployeeService: 7050 ms (total 7050 ms)

I cannot believe it take more than 7 seconds just to open a new Activity. I add a log in onCreate() but see it only take 5ms to finish onCreate.

Can anyone tell me how to find the root of this problem?

like image 452
anticafe Avatar asked May 14 '11 16:05

anticafe


1 Answers

You should move the code Html.fromHtml(desc); to a thread to have it asynchronous. This thread can safely be started during the onCreate() of the newly opened Activity.

At the end of that thread, you can run tvDesc.setText() from the UI thread:

class ExampleThread extends Thread {
    @Override
    public void run() {
         final Spanned spannedText = Html.fromHtml(desc);

         yourNewlyOpenedActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvDesc.setText(spannedText);
                }
         });
    }
}

More generally, 7 seconds on a device maybe means 20 on another, so beware the ANR!

(Edited further to Boy's comment below, the former version of this answer was no longer accurate/valid)

like image 107
Shlublu Avatar answered Oct 03 '22 12:10

Shlublu