Home > Mobile >  Why starting the Activity by an intent (Intent.ACTION_VIEW) doesn't always start a new activity
Why starting the Activity by an intent (Intent.ACTION_VIEW) doesn't always start a new activity

Time:09-02

I have two Android applications.

The first application is the "browser". It gets an URL and displays it in a WebView. The corresponding activity is declared as:

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="http" />
            <data android:scheme="https" />
        </intent-filter>
    </activity>
    

The second application has a few buttons. Tapping each button opens the first application and sends the URL to it using Intent.ACTION_VIEW:

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse(urlString);
intent.setData(uri);
intent.setComponent(new ComponentName("com.custom.browser", "com.custom.browser.MainActivity"));
startActivity(intent);

I expect this code to start a new activity as per https://developer.android.com/reference/android/app/Activity. So the browser application retrieves the URL in onCreate() by using the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    Intent intent = getIntent();
    if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
        displayUrl(intent.getDataString());
    }
    ...
}

However I found that sometimes onCreate() is not called. After calling startActivity(intent), the browser application is just brought to the front, therefore displaying a previous URL.

I can override this behavior by moving the intent retrieval code in the onResume().

However I'd like to understand what am I doing wrong? Shouldn't the method startActivity(Intent) always start a new activity and always call onCreate(), as suggested by the Android documentation?

CodePudding user response:

I expect this code to start a new activity

That is not necessarily what will happen.

However I found that sometimes onCreate() is not called. After calling startActivity(intent), the browser application is just brought to the front,

Yes, that will happen if the activity you are starting is already running at the front of a task. See the documentation for tasks.

I can override this behavior by moving the intent retrieval code in the onResume().

That will not work. Override onNewIntent() and get the new Intent there. Or, adjust the flags in your Intent, or adjust the manifest settings for the activity that you are starting, as is discussed in the documentation for tasks.

  • Related