点击按钮打开Goog​​le URL

时间:2016-10-16 12:46:44

标签: android

我有一个按钮,当我点击此按钮时它会为我打开谷歌,但是当我运行我的代码时说不幸它停止了

public class MyActivity extends Activity {

Context myContext=null;

ConnectivityManager connectMngr=(ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo=connectMngr.getActiveNetworkInfo();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button=(Button)findViewById(R.id.btnCall);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {if (netInfo==null || netInfo.isAvailable()==false||netInfo.isConnected()==false)
    {
        Toast.makeText(getApplicationContext(),"No Internet!!",Toast.LENGTH_LONG);
    }
        else
        {
            Toast.makeText(getApplicationContext(),"You are Connected", Toast.LENGTH_LONG);
            Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com"));

            startActivity(intent);
    }
}
});
    }   

1 个答案:

答案 0 :(得分:0)

有两个问题

我。在 AndroidManifest.xml

中授予权限

II。初始化 MainActivity

中的上下文

<强>的AndroidManifest.xml

授予这些权限

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

<强> MainActivity

public class MainActivity extends Activity {

    // initialize the  objects
    Context myContext = null;
    ConnectivityManager connectMngr ;
    NetworkInfo netInfo ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // passing this activity as the context
            myContext = MainActivity.this;
        // initializing the ConnectivityManager and NetworkInfo class objects
            connectMngr = (ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            netInfo = connectMngr.getActiveNetworkInfo();

        Button button=(Button)findViewById(R.id.btnCall);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {if (netInfo==null || netInfo.isAvailable()==false||netInfo.isConnected()==false)
            {
                Toast.makeText(getApplicationContext(),"No Internet!!",Toast.LENGTH_LONG);
            }
            else
            {
                Toast.makeText(getApplicationContext(),"You are Connected", Toast.LENGTH_LONG);

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

                startActivity(intent);
            }
    }
});}
   }