![](/img/trans.png)
[英]Android RactiveNetwork crashing app when no strong network
[英]App crashing when trying to check network connection
我剛剛開始做一些Android編程,因為我為手機下載了AIDE。 我試圖制作一個需要連接到網站的應用程序,但是每次我運行該應用程序並嘗試進行任何與網絡相關的操作時,它都會崩潰。
我已經在清單文件中設置了INTERNET和ACCESS_NETWORK_STATE的權限。
我將顯示錯誤的日志,但是我不知道如何使用AIDE應用程序或在android設備上執行此操作,因為我無法訪問計算機上的正確IDE。
幫助將不勝感激
public class MainActivity extends Activity{
private TextView text;
@Override
public void onCreate ( Bundle savedInstanceState ){
super onCreate( savedInstanceState );
setContextView( R.layout.main );
textView = ( TextView )findViewById( R.id.myText );
}
public void checkConn(){
ConnectivityManager connMgr = ( ConnectivityManager ) getSystemService ( Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr getActiveNetworkInfo();
if ( networkInfo != null && networkInfo.idconnected() ){
textView.setText( "conection" );
}else{
textView.setText( "no connection" );
}
編輯:我修復了檢查連接問題,但是現在我添加了連接到所需網站的方法,現在我的應用程序再次崩潰。
private void makeConnection(){
try{
URL url = new URL("website");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
}catch (MalformedURLException e) {
textView.setText( "no connection" );
}catch ( IOExcpetion e ){
textView.setText( "no connection" );
}
}
嘗試這個:
MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main );
textView = ( TextView )findViewById( R.id.myText );
checkConn();
}
public void checkConn(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
textView.setText( "conection" );
}else{
textView.setText( "no connection" );
}
}
}
main.xml中:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.SPTechnos.ambassador.Home"
tools:ignore="MergeRootFrame" >
<TextView
android:id="@+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
不要忘記在應用程序清單中添加此權限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
你是這樣定義的
private TextView text
而您正在使用
textView = ( TextView )findViewById( R.id.myText );
然后肯定是崩潰。 像這樣改變
private TextView textView;
並嘗試運行並檢查...
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.