2011-10-07 74 views
0

我在这里遇到了一些问题,需要一些帮助。在android中建立互联网连接

我想从我已经实现的给定坐标获取位置地址。 我的项目检查互联网连接,如果连接不可用,应用程序将显示警报对话框,使用“重试”或“手动”配置。 这就是工作正常,但我启用互联网连接从WiFi或移动数据连接后,该应用程序得到fc,因为空指针异常。

我已经在真正的设备上测试过,经过如此多的尝试,它的工作正常。 如何告诉手机连接并检测到正在建立连接,然后等待连接建立,然后成功加载其数据?

在我的示例中,我的手机已启用了其无线电收音机,但在WPA2握手结束之前,我已设法启动我的活动。我刚刚重新开始活动,因为wifi链接已建立,所以它没有问题;但我希望能够检测到wifi链接实际上正在尝试连接,并等待它连接。 这是我的应用程序的代码:

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(); 
} 
    } 

回答

0

你可以向手机,如果它的连接:

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

我会尝试,。我很困惑,使用处理程序......但无论如何 – mdedewa65