没有互联网时不显示对话框

时间:2015-01-28 07:58:40

标签: android

您好,在下面的代码点击登录按钮与互联网工作fine.suppose没有互联网连接,它没有工作我想显示diaglog没有互联网连接。

任何人都可以帮助我解决这个问题。

Login1.java

public class Login1 extends Activity {  

    protected static final int NOT_CONNECTED_TO_SERVICE = 0;
    protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
    public static final String AUTHENTICATION_FAILED = "0";
    public static final String FRIEND_LIST = "FRIEND_LIST";
    protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2 ;
    protected static final int NOT_CONNECTED_TO_NETWORK = 3;
    private EditText usernameText;
    private EditText passwordText;
    private Button cancelButton;
    private IAppManager imService;
    public static final int SIGN_UP_ID = Menu.FIRST;
    public static final int EXIT_APP_ID = Menu.FIRST + 1;


    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {

            imService = ((IMService.IMBinder)service).getService();  

            if (imService.isUserAuthenticated() == true)
            {
                Intent i = new Intent(Login1.this, FriendList.class);                                                               
                startActivity(i);
                Login1.this.finish();
            }
        }

        public void onServiceDisconnected(ComponentName className) {

            imService = null;
            Toast.makeText(Login1.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };

    Boolean isInternetPresent = false;
    ConnectionDetector cd;
    private ProgressDialog progressDialog; 

    /** Called when the activity is first created. */   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    


        startService(new Intent(Login1.this,  IMService.class));            


        setContentView(R.layout.login_screen);
        setTitle("Login");

        Button loginButton = (Button) findViewById(R.id.login);
        cancelButton = (Button) findViewById(R.id.cancel_login);
        usernameText = (EditText) findViewById(R.id.userName);
        passwordText = (EditText) findViewById(R.id.password);        

        loginButton.setOnClickListener(new OnClickListener(){
            @SuppressWarnings("deprecation")
            public void onClick(View arg0) 
            {
                 new LoadViewTask().execute(); 



                   isInternetPresent = cd.isConnectingToInternet();
                   if (!isInternetPresent) {
                       showAlertDialog(Login1.this, "No Internet Connection",
                               "You don't have internet connection.", true);

                       return;


                   }
                if (imService == null) {
                    Toast.makeText(getApplicationContext(),R.string.not_connected_to_service, Toast.LENGTH_LONG).show();

                    return;
                }
                else if (imService.isNetworkConnected() == false)
                {
                    Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();
                    showDialog(NOT_CONNECTED_TO_NETWORK);

                }
                else if (usernameText.length() > 0 && 
                    passwordText.length() > 0)
                {

                    Thread loginThread = new Thread(){
                        private Handler handler = new Handler();
                        @Override
                        public void run() {
                            String result = null;
                            try {
                                result = imService.authenticateUser(usernameText.getText().toString(), passwordText.getText().toString());
                            } catch (UnsupportedEncodingException e) {

                                e.printStackTrace();
                            }
                            if (result == null || result.equals(AUTHENTICATION_FAILED)) 
                            {

                                handler.post(new Runnable(){
                                    public void run() { 
                                        Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();


                                    }                                   
                                });

                            }
                            else {


                                handler.post(new Runnable(){
                                    public void run() {                                     
                                        Intent i = new Intent(Login1.this, FriendList.class);                                               

                                        startActivity(i);   
                                        Login1.this.finish();
                                    }                                   
                                });

                            }

                        }
                    };
                    loginThread.start();

                }
                else {

                    Toast.makeText(getApplicationContext(),R.string.fill_both_username_and_password, Toast.LENGTH_LONG).show();

                }               
            }           
        });

        cancelButton.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) 
            {                   
                imService.exit();
                finish();

            }

        });


    }

    @Override
    protected Dialog onCreateDialog(int id) 
    {       
        int message = -1;       
        switch (id) 
        {
            case NOT_CONNECTED_TO_SERVICE:
                message = R.string.not_connected_to_service;            
                break;
            case FILL_BOTH_USERNAME_AND_PASSWORD:
                message = R.string.fill_both_username_and_password;
                break;
            case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
                message = R.string.make_sure_username_and_password_correct;
                break;
            case NOT_CONNECTED_TO_NETWORK:
                message = R.string.not_connected_to_network;
                break;
            default:
                break;
        }

        if (message == -1) 
        {
            return null;
        }
        else 
        {
            return new AlertDialog.Builder(Login1.this)       
            .setMessage(message)
            .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                }
            })        
            .create();
        }
    }

    @Override
    protected void onPause() 
    {
        unbindService(mConnection);
        super.onPause();
    }

    @Override
    protected void onResume() 
    {       
        bindService(new Intent(Login1.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);

        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {     
        boolean result = super.onCreateOptionsMenu(menu);

         menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
         menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);


        return result;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch(item.getItemId()) 
        {
            case SIGN_UP_ID:
                Intent i = new Intent(Login1.this, SignUp.class);
                startActivity(i);
                return true;
            case EXIT_APP_ID:
                cancelButton.performClick();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @SuppressWarnings("deprecation")
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();


        alertDialog.setTitle(title);


        alertDialog.setMessage(message);


        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);


        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });


        alertDialog.show();
    }

    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
             progressDialog = ProgressDialog.show(Login1.this,"Loading...",  
                    "Loading application View, please wait...", false, false);  
          progressDialog.show(); 
        }  


        @Override  
        protected Void doInBackground(Void... params)  
        {  

            try  
            {  

                synchronized (this)  
                {  

                    int counter = 0;  

                    while(counter <= 4)  
                    {  

                        this.wait(850);  

                        counter++;  

                        publishProgress(counter*25);  
                    }  
                }  
            }  
            catch (InterruptedException e)  
            {  
                e.printStackTrace();  
            }  
            return null;  
        }  


        @Override  
        protected void onProgressUpdate(Integer... values)  
        {  

            progressDialog.setProgress(values[0]);  
        }  

        @Override  
        protected void onPostExecute(Void result)  
        {  

            progressDialog.dismiss();  


        }  

    }  

2 个答案:

答案 0 :(得分:1)

添加此功能

public static boolean CheckInternet(Context context) {
        ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return wifi.isConnected() || mobile.isConnected();
    }

此功能检查wifi或移动网络(如果可用),如果否,则返回true

并替换它:

if (!isInternetPresent) {
        showAlertDialog(Login1.this, "No Internet Connection",
        "You don't have internet connection.", true);
return;
}

通过此代码:

if (!CheckInternet(this)) {
 new AlertDialog.Builder(this)
 alertDialog.setTitle("Info");
 alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int which) {
     finish();
   }
});

alertDialog.show();
  return;
                   }

答案 1 :(得分:0)

正如你所说:

  

我想显示diaglog,没有互联网连接。

使用此功能:

public static boolean isNetworkAvailable() {
      ConnectivityManager cm = (ConnectivityManager)  getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = cm.getActiveNetworkInfo();
      return netInfo != null && netInfo.isConnectedOrConnecting();
    }

并在您的代码中检查互联网连接:

if (!isNetworkAvailable()) {
    // show your dialog here 
}