Android onNewIntent Uri is always null

2019-02-18 18:18发布

问题:

In my activity's onNewIntent() method, getIntent().getData(); is always null. It definitely goes to this method before going to onCreate() or any other lifecycle function. It returns here from a browser, I don't know why getIntent().getData() is null though.

this activity starts the browser like this context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));

and returns here

@Override
public void onNewIntent(Intent intent){
    super.onNewIntent(intent);

    Uri uri = getIntent().getData();
    if (uri != null && uri.toString().startsWith(TwitterConstants.CALLBACK_URL)) {...}
}

but uri is always null.

manifest stuff:

  <activity
        android:name="myapp.mypackage.TweetFormActivity"
        android:configChanges="orientation|keyboardHidden"
        android:label="@string/app_name"
        android:launchMode="singleInstance"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.Black.NoTitleBar">
         <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="oauth" android:host="myapp"/>
        </intent-filter>
        </activity>

static final String CALLBACK_URL = "oauth://myapp";

what am I missing here? thanks

回答1:

You should call getData() for the intent argument or perform setIntent(intent) before obtaining URI. onNewIntent() doesn't set new intent automatically.

UPDATE: So, here're two ways that you can implement onNewIntent(). The first replaces the old intent with the new one, so when you call getIntent() later, you will receive the new intent.

@Override
protected void onNewIntent(final Intent intent) {
    super.onNewIntent(intent);
    // Here we're replacing the old intent with the new one.
    setIntent(intent);
    // Now we can call getIntent() and receive the new intent.
    final Uri uri = getIntent().getData();
    // Do something with the URI...
}

The second way is to use data from the new intent leave the old one as-is.

@Override
protected void onNewIntent(final Intent intent) {
    super.onNewIntent(intent);
    // We do not call setIntent() with the new intent,
    // so we have to retrieve URI from the intent argument.
    final Uri uri = intent.getData();
    // Do something with the URI...
}

Of course, you can use a combination of two variants, but do not expect to receive the new intent from getIntent() until you explicitly set it with setIntent().