Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android:无法获取更新的位置_Android - Fatal编程技术网

android:无法获取更新的位置

android:无法获取更新的位置,android,Android,我是java和android新手,我正在构建一个应用程序,通过短信发送用户的当前位置,但我的代码总是发送相同的位置。当我从代码中删除最后一个已知位置时,我没有得到任何位置。请允许我谦虚地请求解决我的问题 public class AlarmReceiver extends BroadcastReceiver implements LocationListener { long time = 5 * 1000; long distance = 10; boolean isGPSEnabl

我是java和android新手,我正在构建一个应用程序,通过短信发送用户的当前位置,但我的代码总是发送相同的位置。当我从代码中删除最后一个已知位置时,我没有得到任何位置。请允许我谦虚地请求解决我的问题

public class AlarmReceiver extends BroadcastReceiver implements LocationListener  {


long time = 5 * 1000; 
long distance = 10; 
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
Location location;
String device_id;
double latitude ;
double longitude;

// flag for GPS status
boolean canGetLocation = false;

    String phoneNo = "+923362243969";


@SuppressWarnings("unused")
@SuppressLint("NewApi") 
@Override
public void onReceive(Context context, Intent intent) {

    System.out.println("alarm receiver....");
    Intent service = new Intent(context, MyService.class);
    context.startService(service);

    //Start App On device restart
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
    Intent App = new Intent(context, MainActivity.class);
    App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(App);
    }


    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    device_id = tm.getDeviceId();  // returns IMEI number  

    try {
        LocationManager   locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
             // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (isNetworkEnabled) {
               locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time,distance, this);
               Log.d("Network", "Network");
               latitude = location.getLatitude();
               longitude = location.getLongitude();    
               String Text =  " From Network: Latitude = " + latitude  +" Longitude = " + longitude + " Device Id: " + device_id;
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, Text, null, null);
                Log.i("Send SMS", "");
                this.abortBroadcast(); 

                    }
                }
            }


            else {
              if  (isGPSEnabled) {
                    if (location == null) {
                     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,time,distance, this);
                       Log.d("GPS Enabled", "GPS Enabled");
                       latitude  =  location.getLatitude();
                       longitude =  location.getLongitude();
                       String Text =  " From GPS: Latitude = " + latitude +" Longitude = " + longitude + " Device Id: " + device_id;
                            SmsManager smsManager = SmsManager.getDefault();
                            smsManager.sendTextMessage(phoneNo, null, Text, null, null);
                            Log.i("Send SMS", "");
                            this.abortBroadcast(); 
                            }                    

                        }
                    }       

               }  

            }    


    } catch (Exception e) {

        //  Toast.makeText(context, "no connection", Toast.LENGTH_LONG).show();
          e.printStackTrace();
    }                         }     
       @Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
}

将更新的位置设置为位置对象:

public void onLocationChanged(Location location) {
   this.location = location;
}

在Android上有多种获取位置的方法,每当你请求它试图从GPS获取的位置时,如果它无法获取,你需要从网络获取。在网络位置的情况下,由于网络的位置是从附近的塔楼获得的,所以大部分时间你们会得到相同的位置

你可以用谷歌的FuseAPI来检查最佳位置


关于

步骤1:创建类GPSTracker extends Service implemets LocationListener

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }       
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS Settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}
步骤2:创建一个活动并调用上面的类

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gps);
    mTextView = (TextView) findViewById(R.id.tv);
    gps = new GPSTracker(AndroidGPSTrackingActivity.this);

    if (gps.canGetLocation()) {

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();


        mTextView.setText("Your Location is - \nLat: " + latitude
                + "\nLong: " + longitude);
        Toast.makeText(
                getApplicationContext(),
                "Your Location is - \nLat: " + latitude + "\nLong: "
                        + longitude, Toast.LENGTH_LONG).show();
    } else {
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
    }
}

如果您仍然面临任何问题,请随时恢复。

在onLocationChanged方法中更新您的位置。谢谢,但我必须使用广播接收器扩展代码。使用context.startServicenew Intentcontext,xyz.class从广播接收器启动服务;谢谢,我还想删除LastknownLocation,因为我永远不想获取最后一个位置。请允许我请求您编辑我的代码。如果您的问题没有得到解决,请不要批准ans。这是我在代码中没有提到的第二个问题。我是否应该问一个新问题。禁止提问。。你在别的地方有空吗?