2016-10-16 144 views
0

我有一个按钮,当我点击这个按钮,它会打开谷歌对我来说,但是当我运行我的代码,不幸的是说,它停止按钮打开谷歌URL点击

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

可能有很多理由让_ “不幸的是,它停止了”厄罗河所以请[编辑](http://stackoverflow.com/posts/40070406/edit)你的问题,并发布logcat错误。 – Shashanth

回答

0

有两个问题

i。授予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); 
      } 
    } 
});} 
    }