對於activity,我們可以註冊intent-filter聲明自己對什麼樣的intent感興趣,網頁或其它App就能通過intent來打開我們的App並傳遞參數了,intent-filter裏的action,category,data必須都匹配。
<activity android:name=".TestActivity">
<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="testapp"
android:host="testmodule"
android:path="/showtitle"
android:port="8000" />
</intent-filter>
</activity>
通過網頁打開:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<a href="testapp://testmodule:8000/showtitle?query1=1&title=hello">打開APP</a>
</body>
<html>
通過其它App打開:
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("testapp://testmodule:8000/showtitle?query1=1&title=hello"));
startActivity(intent);
在App中獲取傳遞的參數:
public class TestActivity extends AppCompatActivity {
private static String TAG="TestActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Uri uri=getIntent().getData();
if (uri!=null){
String scheme=uri.getScheme();
String host=uri.getHost();
int port=uri.getPort();
String path=uri.getPath();
String query=uri.getQuery();
String title=uri.getQueryParameter("title");
Log.d(TAG,"scheme:"+scheme+",host:"+host+",port:"+port+",path:"+path+",query:"+query+",title:"+title);
}
}
}
2019-09-06 12:01:17.220 6272-6272/com.xy.testapp D/TestActivity: scheme:testapp,host:testmodule,port:8000,path:/showtitle,query:query1=1&title=hello,title:hello