사용자가 AlertDialog 확인 버튼을 클릭 한 후 다음 활동으로 이동하는 방법은 무엇입니까?

user3260468

http://stackoverflow.com 에서 검색 한 후이 질문을해서 죄송합니다 . 그러나 다른 섹션에서 아래 코드를 사용할 때 다음 활동으로 처리 할 수 ​​없습니다.

여기에서 사용자가 인터넷에 연결되어 있지 않으면 경고 대화 상자에 "인터넷에 연결되지 않았습니다"라는 팝업이 표시되고 사용자 가 alertdilog 에서 종료 버튼을 클릭 하면 앱이 닫힙니다. 사용자가 인터넷에 연결되어 있으면 팝업이 경고하고 경고 대화 상자에 "인터넷에 연결되어 있습니다"라는 메시지가 표시되고 사용자가 계속 버튼을 클릭하면 앱이 다음 활동을 계속합니다. 다음 활동을 계속하는 데 문제가 있습니다. 어떻게해야합니까?

아래 코드는 섹션에 표시됩니다.

AndroidDetectInternetConnectionActivity.java의 코드

package com.example.detectinternetconnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AndroidDetectInternetConnectionActivity extends Activity {

 // flag for Internet connection status
Boolean isInternetPresent = false;

    // Connection detector class
ConnectionDetector cd;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 Button btnStatus = (Button) findViewById(R.id.btn_check);

 // creating connection detector class instance
  cd = new ConnectionDetector(getApplicationContext());

    /**
     * Check Internet status button click event
     * */
    btnStatus.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {

            // get Internet status
        isInternetPresent = cd.isConnectingToInternet();

            // check for Internet status
        if (isInternetPresent) {
                // Internet Connection is Present
                // make HTTP requests
        AlertDialog.Builder builder = new AlertDialog.Builder(AndroidDetectInternetConnectionActivity.this);
        builder.setMessage("You have network connection.")
            .setTitle("Internet Connection")
            .setCancelable(false);
    AlertDialog alert = builder.create();
                    alert.setButton("Continue", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which){ 
                          // Do call some activity. Do what you    wish to;
startActivity(new Intent(AndroidDetectInternetConnectionActivity.this,MainActivity2.class));
                           }
                          }); 
                    alert.show();
            }

 else {
                // Internet connection is not present
                // Ask user to connect to Internet
      AlertDialog.Builder builder = new AlertDialog.Builder(AndroidDetectInternetConnectionActivity.this);
       builder.setMessage("You need a network connection to use this application. Please turn on mobile network or Wi-Fi in Settings.")
         .setTitle("No Internet Connection")
         .setCancelable(false);
    AlertDialog alert = builder.create();
    alert.setButton2("Exit", new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int which) {
                         //close the program
                    AndroidDetectInternetConnectionActivity.this.finish();
        }
            });
                      // Showing Alert Message
               alert.show();
                 }
        }

ConnectionDetector.java 패키지의 코드 com.example.detectinternetconnection;

import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
}

AndroidManifest.xml의 코드

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.detectinternetconnection"
  android:versionCode="1"
  android:versionName="1.0" >

 <uses-sdk android:minSdkVersion="8" />

 <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".AndroidDetectInternetConnectionActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MainActivity2"></activity>
  </application>

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

 </manifest>

내가 어디에서 잘못하고 있는지 말해줘?

Ranjit

전체 코드는 괜찮지 만 create ()를 통해 마지막으로 alertdialog를 초기화하십시오.

    if (isInternetPresent) {              
    // Internet Connection is Present
   // make HTTP requests
    AlertDialog.Builder builder = new   AlertDialog.Builder(AndroidDetectInternetConnectionActivity.this);
    builder.setMessage("You have network connection.")
        .setTitle("Internet Connection")
        .setCancelable(false);

                alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which){ 
                      // Do call some activity. Do what you    wish to;
         startActivity(new  Intent(AndroidDetectInternetConnectionActivity.this,MainActivity2.class));
                  }
               }); 
          AlertDialog alert = builder.create();
                alert.show();

편집하다

총 활동 클래스입니다.

package com.example.detectinternetconnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AndroidDetectInternetConnectionActivity  extends Activity implements   OnClickListener {

Boolean isInternetPresent = false;
ConnectionDetector cd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    Button btnStatus = (Button) findViewById(R.id.btnStatus);
    cd = new ConnectionDetector(getApplicationContext());
    btnStatus.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    isInternetPresent = cd.isConnectingToInternet();
    if (isInternetPresent) {

        AlertDialog alert;
        AlertDialog.Builder builder = new AlertDialog.Builder(
                AndroidDetectInternetConnectionActivity .this);
        builder.setTitle("Internet Connection");
        builder.setCancelable(false);

        builder.setPositiveButton("Continue",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        startActivity(new Intent(AndroidDetectInternetConnectionActivity .this,
                                MainActivity2 .class));
                    }
                });

        alert = builder.create();
        alert.show();
    }

    else {

        AlertDialog alert;
        AlertDialog.Builder builder = new AlertDialog.Builder(
                AndroidDetectInternetConnectionActivity .this);
        builder.setTitle("No Internet Connection");
        builder.setMessage("Please Connect To Internet");
        builder.setCancelable(false);

        builder.setPositiveButton("Exit",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

        alert = builder.create();
        alert.show();
    }
}

}

나는 당신이 다른 수업을 돌볼 것이라고 생각합니다. 약간의 지식 은 개발자 사이트 Android Dialog 튜토리얼을 참조 할 수 있습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관