anticafe
anticafe

Reputation: 6892

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?

Upvotes: 8

Views: 22460

Answers (3)

Shlublu
Shlublu

Reputation: 11027

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)

Upvotes: 3

Boy
Boy

Reputation: 7487

Shlublu's answer is incorrect, you are not allowed to do UI updates from non-UI threads!

It seems to work at first, but that is just luck, timing.

just a quick ugly test proves that it will go wrong at the 'right' timing. Here I set a text every 100 ms. Will crash in about 1 second:

      new Thread() {

        @Override
        public void run() {
            while (true) {
                someTextView.setText("bla");

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();

It will throw this error: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

I think you should execute the Html.fromHtml(desc) via an AsyncTask or RxJava

Upvotes: 1

Kundan Chaudhary
Kundan Chaudhary

Reputation: 833

your open new activity code put in Thread . and run code may be less time to required open another activity..may be helpfully.

Upvotes: 0

Related Questions