简体   繁体   English

单击Android按钮重定向到URL

[英]Re-direct to an URL on clicking Android Button

I tried to open a webpage on clicking a button. 我试图在单击按钮时打开网页。 But, Its not working. 但是,它不起作用。 This is my code: 这是我的代码:

ImageButton fbButton = (ImageButton) findViewById(R.id.fb);
    fbButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                Intent viewIntent = new Intent("Intent.ACTION_VIEW", Uri.parse("http://www.facebook.com"));
                startActivity(viewIntent);
        }
    });

Its always going to catch statement. 它总是要抓住声明。

And Here it is Manifest file permission code: 这是清单文件的权限代码:

   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Error Log: 错误日志:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.krish.me, PID: 4532
              android.content.ActivityNotFoundException: No Activity found to handle Intent { act=Intent.ACTION_VIEW dat=http://www.facebook.com }

Thank you in Advance :) 先感谢您 :)

Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com"));

使用Intent.ACTION_VIEW代替"android.intent.action.view"

If you want to open an URL with Intent just use Intent.ACTION_VIEW in place of android.intent.action.view 如果您想使用Intent打开URL,只需使用Intent.ACTION_VIEW代替android.intent.action.view

Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com"));

Your code will become like this - 您的代码将变成这样-

ImageButton fbButton = (ImageButton) findViewById(R.id.fb);
    fbButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/"));
                startActivity(viewIntent);
            }
            catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Can't connect to Internet",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

Make sure you has Internet Permission added in the AndroidManifest file. 确保您在AndroidManifest文件中添加了Internet权限。

<uses-permission android:name="android.permission.INTERNET" /> 

The problem is i think you dont have any app that can open URLs (ie browsers) installed in your phone. 问题是我认为您没有任何可以打开手机中安装的URL(即浏览器)的应用程序。

Try this, 尝试这个,

 try {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com"));
        startActivity(Intent.createChooser(intent, "Choose browser"));
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "Can't connect to Internet",
                Toast.LENGTH_SHORT).show();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM