Android onNewIntent Uri始终为null

CQM*_*CQM 3 android uri callback android-intent twitter4j

在我的activity的onNewIntent()方法中, getIntent().getData();始终为null.在转到onCreate()或任何其他生命周期函数之前,它肯定会使用此方法.它从浏览器返回此处,我不知道为什么它getIntent().getData()是null.

此活动会像这样启动浏览器 context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));

并返回此处

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

    Uri uri = getIntent().getData();
    if (uri != null && uri.toString().startsWith(TwitterConstants.CALLBACK_URL)) {...}
}
Run Code Online (Sandbox Code Playgroud)

但是uri总是空的.

明显的东西:

  <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";
Run Code Online (Sandbox Code Playgroud)

我在这里想念的是什么?谢谢

Mic*_*ael 12

你应该调用getData()intent参数或进行setIntent(intent)获取URI之前.onNewIntent()不会自动设置新意图.

更新:所以,这有两种方法可以实现onNewIntent().第一个用新的意图替换旧意图,所以当你getIntent()稍后调用时,你将收到新的意图.

@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...
}
Run Code Online (Sandbox Code Playgroud)

第二种方法是使用来自新意图的数据,保留旧的意图.

@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...
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用两种变体的组合,但在您明确设置它之前,不要期望接收新的意图getIntent()setIntent().