2016-10-16 187 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); 
      } 
    } 
});} 
    }