1、建立一個Intents項目,給該項目添加一個新類,命名為MyBrowserActivity,在res/layout檔案夾下新增一個browser.xml;
2、在AndroidManifest.xml檔案中添加如下代碼:
添加許可權:
<uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.INTERNET" />
<activity android:name=".MyBrowserActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="net.zenail.MyBrowser" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> </intent-filter> </activity>
action:動作;category:類別;data:指明擷取的資料類型。
3、在main.xml檔案中添加三個Button:
<Button android:id="@+id/btn_webbrowser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickWebBrowser" android:text="Web Browser" /> <Button android:id="@+id/btn_makecalls" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickMakeCalls" android:text="Make Calls" /> <Button android:id="@+id/btn_launchMyBrowser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickLaunchMyBrowser" android:text="Launch My Browser" />
4、在IntentsActivity.java檔案中添加三個Button對應的三個點擊方法:
public void onClickWebBrowser(View v) {Intent intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://網址"));//此處輸入百度網址,CSDN不讓加連結...//使用createChooser()的好處://1、將顯示的選擇對話方塊的標題改掉,且沒有了Use by default for this action選項//2、當沒有活動與程式的Intent對象匹配時,應用程式不會崩潰//startActivity(intent.createChooser(intent, "Open URL using..."));startActivity(intent);}public void onClickMakeCalls(View v) {Intent intent = new Intent(android.content.Intent.ACTION_DIAL,Uri.parse("tel:+651234567"));startActivity(intent);}public void onClickLaunchMyBrowser(View v) {Intent intent = new Intent("net.zenail.MyBrowser");intent.setData(Uri.parse("http://網址"));//此處輸入百度網址,CSDN不讓加連結...startActivity(intent);}
5、在browser.xml中添加一個WebView:
<WebView android:id="@+id/WebView01" android:layout_width="wrap_content" android:layout_height="wrap_content" />
6、在MyBrowserActivity.java檔案中添加如下代碼,實現瀏覽網頁功能:
public class MyBrowserActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.browser);Uri url = getIntent().getData();WebView webView = (WebView) findViewById(R.id.WebView01);webView.setWebViewClient(new Callback());webView.loadUrl(url.toString());}private class Callback extends WebViewClient {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// TODO Auto-generated method stubreturn false;}}}
7、運行一下,效果如下:
點擊第三個按鈕:
點擊第一個按鈕:
若想完善意圖篩選器,則在IntentsActivity.java的onClickWebBrowser()方法中添加createChooser()方法:
startActivity(intent.createChooser(intent, "Open URL using..."));
添加後的效果如下:
這時即可選擇你想要選擇的應用程式即可~
附、使用createChooser()的好處:
1、將顯示的選擇對話方塊的標題改掉,且沒有了Use by default for this action選項;
2、當沒有活動與程式的Intent對象匹配時,應用程式不會崩潰。