有時候我們開發(fā)的應(yīng)用希望讓其他應(yīng)用也可以訪問,Android平臺而言,可以通過Uri(統(tǒng)一資源標識符Uniform Resource Identifier)來實現(xiàn).
Android中 URI的組成部分scheme, authority and path,其中authority又分為host和port激捏。格式如下: scheme://host:port/path
舉個實際的例子:
content://com.dx.test:2020/folder/myfolder/dir
其中scheme 對應(yīng) content://
authority 對應(yīng) com.dx.test:2020
host 對應(yīng) com.dx.test
port 對應(yīng) 2020
path 對應(yīng) /folder/myfolder/dir
這時候我們想到在mainifest.xml里面定義的activity標簽下的intent-filter子標簽data里面的各個屬性,實際上與上面是有對應(yīng)關(guān)系的
<data android:host="string"
android:mimeType="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:port="string"
android:scheme="string" />
比如有在A應(yīng)用程序的mainifest.xml中有這么個Activity
<activity android:name=".TestActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sharetest" android:host="data" />
</intent-filter>
</activity>
如上所示,在data里設(shè)置了 scheme和host填抬,則該Activity可以接收和處理類似于 "sharetest://data/XXX"的鏈接蕾管。
在A應(yīng)用程序的TestActivity中編寫處理Scheme的邏輯
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
/**
* Created by dengxuandeng on 16-3-9.
*/
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
Intent a = getIntent();
Log.d("scheme", a.toString());
}
}
這里為了方便 直接用log打出來了.
到這里 A 程序就準備OK了.
在B應(yīng)用程序中,可以直接寫一個函數(shù) 調(diào)起A引用程序中的這個TestActivity
public void gotoScheme(String url) {
Intent intent = new Intent(Intent.ACTION_DEFAULT, Uri.parse(url));
Bundle bundle = new Bundle();
intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.startActivity(intent);
}
調(diào)起的時候直接寫
gotoScheme("sharetest://data/123141")
那么使用B程序使用Scheme調(diào)起 A程序的TestActivity的時候,可以看到A程序的TestActivity打出來的log
03-09 11:35:48.126 1088-1088/com.dear.schemetest D/scheme: Intent { act=android.intent.action.VIEW dat=sharetest://data/123141 flg=0x24000000 cmp=com.dear.schemetest/.TestActivity (has extras) }