使用<intent-filter>
您指定您的活动应该处理的网址。一旦系统检测到您的应用程序中的活动能够处理该 url,它就会打开该活动,您就可以获取数据Extra
或.getData()
对象。
在您的 AndroidManifest.xml 文件中:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter android:label="My app preview">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="www.myapp.com/api/id"
android:pathPrefix="/api/" <!-- optional, you can skip this field if your url doesn't have prefix-->
android:scheme="http"/>
<data
android:host="www.myapp.com/api/id"
android:pathPrefix="/api/" <!-- optional, you can skip this field -->
android:scheme="https"/>
</intent-filter>
</activity>
在您的活动中:
public class MainActivity extends Activity {
Bundle bundle = getIntent.getExtras();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleExtra(getIntent());
}
// If your app is in opened in background and you attempt to open an url, it
// will call this function instead of onCreate()
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleExtra(getIntent());
}
private void handleExtra(Intent intent) {
String myID = intent.getData().getLastPathSegment();
....
}
}