首页 文章

意图打开网址会导致浏览器输入错误的网址

提问于
浏览
1

我试图使用intent在浏览器中打开一个URL .

我的代码是

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.onair99.com"));
startActivity(i);

这会导致我尝试打开这样的浏览器后尝试的任何浏览器出错:

http://http//onair99.com//

据我所知,我只遇到过这个特定网址的问题 .

有人知道为什么吗?

谢谢 .

2 回答

  • 2

    按照post中提到的那样做

    String url = "http://www.somewebsite.com";
    

    在 生产环境 级别代码中,您可能想要检查URL是以http还是https开头...最好检查一下

    if (!url.startsWith("http://") && !url.startsWith("https://"))  
      url = "http://" + url;
    
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
    

    这是documentation of Intent.ACTION_VIEW.

  • 0

    试试这个代码

    main.xml中

    <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" Go to link" />
    
        </LinearLayout>
    

    MyAndroidAppActivity.java

    import android.app.Activity;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.widget.Button;
    import android.view.View;
    import android.view.View.OnClickListener;
    
    public class MyAndroidAppActivity extends Activity {
    
        Button button;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            addListenerOnButton();
    
        }
    
        public void addListenerOnButton() {
    
            button = (Button) findViewById(R.id.button1);
    
            button.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
    
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.onair99.com"));
                    startActivity(browserIntent);
    
                }
    
            });
    
        }
    
    }
    

    AndroidManifest.xml中

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.mkyong.android"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="10" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:label="@string/app_name"
                android:name=".MyAndroidAppActivity" >
                <intent-filter >
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    

相关问题