开发者

establish internet connection in android

I've got some problem here, and needed some help with it.

I want to get location address from given cordinate that I already achieve. my project check internet connection, if connection not available, the app will show alert dialog, to use "retry" or "manual" configuration. thats work fine, but after I enable the internet connection from wifi or mobile data connection, the app got fc because null pointer exception.

I have tested in real device, after so many tried it works normal. How I can tell the phone to connect and detect that a connection is being made and then wait for the connection to establish, and then load its data successfully?

In my example, my phone has its wifi radio enabled, but I manage to start my Activity before the WPA2 handshaking finishes. I restart my Activity just moments later and it has no problem because the wifi link has been established; but I want to be able to detect that the wifi link is actually trying to connect, and wait for it to connect. this is the code for my app:

    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    import java.util.Timer;
    import java.util.TimerTask;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.net.ConnectivityManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;
    public class db_new_auto extends Activity {
 /**
     * Best location abstract result class
     */
    public static abstract class LocationResult{
     public abstract void gotLocation(Location location);
 }
public class MyLocation{
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    }
    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };
    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

}

// the text fields that users input new data into
EditText    etNama, etKabupaten,etJalan, etLong, etLat, etKeterangan;
// the buttons that listen for the user to select an action
Button      bSave, bCancel;
ImageView   ivAddpicture;
// the class that opens or creates the database and makes sql calls to it
PuraHelper helper;

ProgressDialog dialog;

Location currentLocation;
double currentLatitude;
double currentLongitude;

//private static final int IMAGE_CAPTURE = 0;
private static final int TAKE_PICTURE = 0;
private Uri imageUri;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_new);

     dialog = ProgressDialog.show(db_new_auto.this, "Getting Location", 
                "Loading, Please wait...", true);

     MyLocation myLocation = new MyLocation();
     myLocation.getLocation(this, locationResult);

     // create the database manager object
     helper = new PuraHelper(this);

     ivAddpicture = (ImageView)findViewById(R.id.ivAddpicture);
     etNama = (EditText)findViewById(R.id.etNama);
     //etKabupaten = (EditText)findViewById(R.id.etKabupaten);
     etJalan = (EditText)findViewById(R.id.etJalan);
     etLong = (EditText)findViewById(R.id.etLong);
     etLat = (EditText)findViewById(R.id.etLat);
     etKeterangan = (EditText)findViewById(R.id.etKeterangan);
     bSave=(Button)findViewById(R.id.bSave);
     bCancel=(Button)findViewById(R.id.bCancel);

     ivAddpicture.setOnClickListener(new View.OnClickListener(){
         public void onClick(View v) {
             addPicture();
         }
     });
     bCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(db_new_auto.this, db_list.class));
            }
        });
    bSave.setOnClickListener(onSave);
}

private View.OnClickListener onSave=new开发者_运维问答 View.OnClickListener() {
    public void onClick(View v) {

            helper.insert(etNama.getText().toString(),
                    //etKabupaten.getText().toString(),
                    etJalan.getText().toString(),
                    etLong.getText().toString(),
                    etLat.getText().toString(),
                    etKeterangan.getText().toString());

        Intent iDatabase = new Intent(getBaseContext(),db_list.class);
        startActivityForResult(iDatabase,0);
    }
};



protected void addPicture() {
    // TODO Auto-generated method stub
    final CharSequence[] items = {"Camera", "Galery"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add picture from?");
    builder.setIcon(R.drawable.ic_setting_36);
    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            if (items[item]=="Camera") {
                //startActivity(new Intent(db_new_auto.this, cam.class));
                //startCamera();
                takePhoto(ivAddpicture);
            }
            else if(items[item]=="Galery"){

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


public void takePhoto(View view) {
    // TODO Auto-generated method stub
     Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(photo));
        imageUri = Uri.fromFile(photo);
        startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ivAddpicture);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}


/*
protected void startCamera() {
    // TODO Auto-generated method stub
    Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
    String fileName = "testphoto.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    values.put(MediaStore.Images.Media.DESCRIPTION,
            "Image capture by camera");
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    imageUri = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    startActivityForResult(intent, IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMAGE_CAPTURE) {
        if (resultCode == RESULT_OK){
            Log.d("ANDRO_CAMERA","Picture taken!!!");

            ivAddpicture.setImageURI(imageUri);

        }
    }
}
*/


public LocationResult locationResult = new LocationResult(){
     private Address location;
    @Override
     public void gotLocation(final Location location){
     // do something

         double lng =  location.getLongitude();
         double lat =  location.getLatitude();

         etLat.setText(""+lng);
         etLong.setText(""+lat);
         dialog.dismiss();

        checkinternetconnection();


}

    private boolean checkinternetconnection() {
        // TODO Auto-generated method stub

        ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
        // ARE WE CONNECTED TO THE NET
        if (conMgr.getActiveNetworkInfo() != null
        && conMgr.getActiveNetworkInfo().isAvailable()
        && conMgr.getActiveNetworkInfo().isConnected()) {   
             double lng =  location.getLongitude();
             double lat =  location.getLatitude();
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            List<Address> addresses = null;
            try {
                addresses = gcd.getFromLocation(lat, lng, 1);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                String address = "";
                if (addresses.size() > 0) {
                for (int index = 0; 
                    index < addresses.get(0).getMaxAddressLineIndex(); index++)
                          address  += addresses.get(0).getAddressLine(index) + " ";
                etJalan.setText(address);
                }
        return true;
        } 
        else {
        Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
        alertRetry();   
        return false;
        }
    }

};

protected void alertRetry() {
    // TODO Auto-generated method stub
    final CharSequence[] items = {"Rety", "Use Manual"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Cannot get current location");
    builder.setIcon(R.drawable.ic_setting_36);
    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            if (items[item]=="Rety") {
                startActivity(new Intent(db_new_auto.this, db_new_auto.class));
            }
            else if(items[item]=="Use Manual"){
                startActivity(new Intent(db_new_auto.this, db_new_man.class));
            }
            finish();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}
    }


You can ask the phone if it's connecting:

    final ConnectivityManager connMgr = (ConnectivityManager)
        ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

final android.net.NetworkInfo wifi =
            connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

final android.net.NetworkInfo mobile =
            connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    final android.net.NetworkInfo network = connMgr.getActiveNetworkInfo();

    if (!network.isConnected() && network.isConnectedOrConnecting()) {
            // trying to connect..sleep for a few or put up a dialog and use a Handler()
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜