2

私はAndroidとJavaの初心者ですが、それほどではありません。この質問がばかげている場合はご容赦ください。**この投稿の形式がひどい場合も申し訳ありません。私はここで新しいことを理解してください。手順はどこにでもありますが、フォローアップ投稿を追加する方法がわからないため、元の投稿を編集して、受け取った新しい情報を追加しました。 。

Androidプロジェクトで、サーバーに接続できるかどうかを確認する必要のあるアクティビティがあります。クリックするとサーバー接続をチェックするコードを実行するボタンがあります。

ボタンをクリックすると、アプリケーションがシャットダウンします(Unfortunately .... has stopped).

必要に応じて、完全なエラーログを提供できます。これが私が持っているコードです:

注:R.id.check_textは、レイアウトXMLのTextViewを参照します

isConnectedToServerメソッドの結果を考慮して、このテキストを変更する必要があります。

public class StartActivity extends Activity {

public static final int timeout = 3000;
public static final String TAG = "StartActivity";
public static final String url = "http://serverIP:port";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_start, menu);
    return true;
}

public boolean isConnectedToServer(String url, int timeout) {
    try {
        URL serverURL = new URL(url);
        URLConnection urlconn = serverURL.openConnection();
        urlconn.setConnectTimeout(timeout);
        urlconn.connect();
        return true;
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    } catch (IllegalStateException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }
    return false;   

}
public void connectionReturn(View view) {
    boolean a;
    a = this.isConnectedToServer(url, timeout);
    if (a == true) {
        EditText edConnStatus = (EditText) findViewById(R.id.check_text);
        edConnStatus.setText("Connection established");

    } else {
        EditText edConnStatus = (EditText) findViewById(R.id.check_text);
        edConnStatus.setText("Connection to server could not be established");
    }

}
}

そしてもちろん、私のレイアウトXMLには、次のようなボタンがあります。

    <Button
    android:id="@+id/bn_checkconnection"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="connectionReturn"
    android:text="@string/checkservconn" /> 

私は与えられることができるどんな助けにも感謝し、そしてすべてに感謝します。

最近の編集: connectionReturnメソッドを変更してパラメーターView view(つまり、connectionReturn(View vw))を設定し、onClickで間違いが発生したので、connectionReturnメソッドを呼び出します。同じエラーは発生しません。新しいエラーが発生します。ボタンをクリックすると、アプリがフリーズし、EclipseがSocket.classを開きます。

ソースが見つかりませんJARファイルc:... \ androidsdk \ platform \ android17\android.jarにソース添付ファイルがありません以下のソースを添付してください...。

Eclipseのデバッグウィンドウビューには、次のメッセージが表示されます。

Thread [<1> main](Suspended(exception NetworkOnMainThreadException))

Socket.connect(SocketAddress、int)line:849<-これはすぐにこれを指します。
HttpConnection。(HttpConnection $ Address、int)行:76 HttpConnection。(HttpConnection $ Address、int、HttpConnection $ 1)行:50
HttpConnection $ Address.connect(int)行:340
HttpConnectionPool.get(HttpConnection $ Address、int)行: 87
HttpConnection.connect(URI、SSLSocketFactory、Proxy、boolean、int)行:128
HttpEngine.openSocketConnection()行:316 HttpEngine.connect()行:311
HttpEngine.sendSocketRequest()行:290
HttpEngine.sendRequest()行:240
HttpURLConnectionImpl.connect()行:81
StartActivity.isConnectedToServer(String、int)行:37 StartActivity.connectionReturn(View)行:50
Method.invokeNative(Object、Object []、Class、Class []、Class、int、boolean)行:使用不可[ネイティブメソッド]
Method.invoke(Object、Object ...)行:511
View $ 1.onClick(View)行:3592 Button(View).performClick()行:4202
View $ PerformClick.run()行:17340 Handler.handleCallback(Message )行:725
ViewRootImpl $ ViewRootHandler(Handler).dispatchMessage(Message)行:92 Looper.loop()行:137 ActivityThread.main(String [])行:5039
Method.invokeNative(Object、Object []、Class、Class []、Class、int、boolean)行:使用不可[ネイティブメソッド]
Method.invoke(Object、Object ...)行:511
ZygoteInit $ MethodAndArgsCaller.run()行:793
ZygoteInit.main(String [])行:560 NativeStart.main(String [])行:使用不可[ネイティブメソッド]

4

2 に答える 2

0

android:onClickプロパティを使用するときはこれを覚えておいてください

android:onClick属性の値、は"isConnectedToServer"、ユーザーがボタンをクリックしたときにシステムが呼び出すアクティビティ内のメソッドの名前です。

(プロジェクトのsrc /ディレクトリにある)Activityクラスを開き、対応するメソッドを追加します。

/**ユーザーが[送信]ボタンをクリックすると呼び出されます*/

public void sendMessage(View view) {
    // Do something in response to button
}

Viewこれには、クラスをインポートする必要があります。

システムがこのメソッドをandroid:onClickに指定されたメソッド名と一致させるには、署名が表示されているとおりである必要があります。具体的には、メソッドは次のことを行う必要があります。

 1). Be public.
 2). Have a void return value.
 3). Have a View as the only parameter (this will be the View that was clicked).
于 2013-01-01T05:14:16.880 に答える
0

この機能を使用して、リンクがアップしているか、インターネットが接続されているかどうかを知ることができます

public boolean isConnected() {
    try {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnected()) {
            // Network is available but check if we can get access from the
            // network.
            URL url = new URL("www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url
                    .openConnection();
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(2000); // Timeout 2 seconds.
            urlc.connect();

            if (urlc.getResponseCode() == 200) // Successful response.
            {
                return true;
            } else {
                Log.d("NO INTERNET", "NO INTERNET");
                showToast("URL down");
                return false;
            }
        } else {
            showToast("No Internet Connection");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
于 2013-01-01T09:03:47.613 に答える