2014-01-21 43 views
1

我是android新手。我能夠從仿真器獲得GPS座標,但是在我的設備中獲得0.0,0.0的經度和緯度。 這是我的代碼。對不起它太長..GPS在設備上返回0.0,0.0作爲經度和緯度,但在仿真器上正常工作

GPSTracker.java

package com.example.spotter; 


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 
double accuracy; 

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

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

// 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 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(); 
          Log.d("GPS Enabled", String.valueOf(latitude)); 
         } 
        } 
       } 
       else{ 
        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(); 
          } 
         } 
        } 
       } 
      } 
     } 

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

    return location; 
} 

public void stopUsingGPS(){ 
    if(locationManager != null){ 
     locationManager.removeUpdates(GPSTracker.this); 
    }  
} 

public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 
public double getAccuracy(){ 
    if(location != null){ 
     accuracy = location.getAccuracy(); 
    } 

    return accuracy; 

} 

public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

public void showSettingsAlert(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    alertDialog.setTitle("GPS is 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) { 
    Log.d("spt", "in loc changed"); 
    /*if (MainService.loststatus > 0) { 

     HttpPost httpPost = new HttpPost(
       "http://spotter.orgfree.com/writegps.php?value=" 
         + String.valueOf(this.getLatitude()) + "," 
         + String.valueOf(this.getLongitude())); 
     // output is the variable you used in your program 
     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 

      httpClient.execute(httpPost); 
      Log.d("spt", "writing coord to file"); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     //Toast.makeText(this, String.valueOf(gps.getLatitude()) + String.valueOf(gps.getLatitude()), 
     // Toast.LENGTH_SHORT).show(); 

    }*/ 

} 

@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; 
} 
} 

MainService.java

package com.example.spotter; 

public class MainService extends Service implements Runnable { 

    String str; 
    Intent i1; 

    static double loststatus = 0; 
    Thread t; 
    //double longi,lati; 
    String provider; 
    Location location; 
    Handler handler = new Handler() { 
      @Override 
      public void handleMessage(Message msg) { 
       Intent i = new Intent(); 
       i.setClass(getApplicationContext(), Locked.class); 
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       startActivity(i); 
       Log.d("spt", "in handler"); 
      } 
     }; 


    @Override 
    public IBinder onBind(Intent arg0) { 

     return null; 
    } 

    @Override 
    public void onCreate() { 

     super.onCreate(); 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show(); 

     super.onDestroy(); 
     stopService(new Intent(getBaseContext(), MainService.class)); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Toast.makeText(this, "Spotter tracking service has been activated.", Toast.LENGTH_SHORT).show(); 
     Notification note=new Notification(R.drawable.ic_launcher, 
       "", 
       System.currentTimeMillis()); 
Intent i=new Intent(this, MainActivity.class); 

i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| 
Intent.FLAG_ACTIVITY_SINGLE_TOP); 

PendingIntent pi=PendingIntent.getActivity(this, 0, 
         i, 0); 

note.setLatestEventInfo(this, "", 
    "", 
    pi); 
note.flags|=Notification.FLAG_NO_CLEAR; 


     t = new Thread(this); 
     t.start(); 
     startForeground(1337, note); 
     return START_STICKY; 
    } 

    public void run() { 

     Looper.prepare(); 

     while (isMyServiceRunning()) { 

      try { 
       Thread.sleep(30000); 

      } catch (InterruptedException e) { 

       e.printStackTrace(); 
      } 


      try { 
       Log.d("spt", "read status started"); 
       if ((Connectivity.isConnected(getApplicationContext()))) { 
        URL urlreadstatus = new URL("http://abc.xyz.com/status.txt"); 
       // Log.d("spt",String.valueOf(URLUtil.isValidUrl("http://abc.xyz.com/status.txt"))); 
        BufferedReader in = new BufferedReader(new InputStreamReader(urlreadstatus.openStream())); 
        str = in.readLine(); 
        if(!str.equals(null)){ 
         Log.d("spt", str); 
        } 
        in.close(); 
        Log.d("spt", "read status complete"); 
       } else { 
        Log.d("spt", "not connected"); 
        break; 
       } 

      } catch (MalformedURLException e1) { 

       e1.printStackTrace(); 
      } catch (IOException e) { 

       Log.d("spt", "IO exception"); 
       str = "11"; 
       e.printStackTrace(); 
      } catch(NullPointerException e){ 
       str="11"; 
      } 
      if (str.equals(null)) { 
       str = "11";    
      } 
      if (str.length() == 1) { 
       loststatus++; 
       if(loststatus %10 ==0){ 
        SendSms s= new SendSms(); 
        Log.d("spt", "ghus gaye"); 
        TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
        String getSimSerialNumber = telemamanger.getSimSerialNumber(); 
        String getSimNumber = telemamanger.getLine1Number(); 
        String no="15555215557"; 
        if (getSimNumber != no) 
        { 
        //Log.d("spt", getSimNumber); 
         Log.d("spt", "ghus gaye dobara"); 

        sendSMS(); 
        } 

       } 

       GPSTracker gps=new GPSTracker(MainService.this); 
       Log.d("spt", "lost status1 requesting location updates"); 
       Toast.makeText(this, String.valueOf(gps.getLatitude()) + String.valueOf(gps.getLatitude()), 
         Toast.LENGTH_SHORT).show(); 

       if(loststatus==1){ 
        handler.sendEmptyMessage(0); 
       } 
       if (loststatus > 0) { 

        HttpPost httpPost = new HttpPost(
          "http://abc.xyz.com/writegps.php?value=" 
            + String.valueOf(gps.getLatitude()) + "," 
            + String.valueOf(gps.getLongitude())); 
        HttpPost httpPost2 = new HttpPost(
          "http://abc.xyz.com/writeaccuracy.php?value=" 
            + String.valueOf(gps.getAccuracy())); 

        // output is the variable you used in your program 
        try { 
         DefaultHttpClient httpClient = new DefaultHttpClient(); 

         httpClient.execute(httpPost); 
         httpClient.execute(httpPost2); 
         Log.d("spt", "writing coord to file"); 
         //gps.stopUsingGPS(); 

        } catch (ClientProtocolException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 


       } 




      } else { 
       loststatus = 0; 
      } 

     } 

    } 
    private boolean isMyServiceRunning() { 
     ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
     for (RunningServiceInfo service : manager 
       .getRunningServices(Integer.MAX_VALUE)) { 
      if ("com.example.spotter.MainService".equals(service.service 
        .getClassName())) { 
       return true; 
      } 
     } 
     return false; 
    } 
    public void sendSMS() { 
     String phoneNumber = "15555215556"; 
     GPSTracker gps=new GPSTracker(MainService.this); 

     String message =String.valueOf(gps.getLatitude())+","+String.valueOf(gps.getLongitude()); 

     Log.d("spt", "in send sms"); 

     // SmsManager smsManager = SmsManager.getDefault(); 
     //smsManager.sendTextMessage(phoneNumber, null, message, null, null); 
    } 

} 

請幫助。

+0

設備上是否啓用GPS?它有天空的好景色嗎? –

+0

您是否在清單中添加了此權限? –

+0

權限已被添加@ZohraKhan –

回答

3

你有幾個邏輯問題在你的代碼

  1. if (isGPSEnabled),你首先詢問當前位置,然後檢查是否所有舊的位置存在。 if (isNetworkEnabled)的情況也是如此。
  2. 要求新位置需要幾秒鐘到20分鐘的時間。因此,所有進一步的步驟都應在onLocationChanged()中完成,而您已將其留空。
  3. 既然你也是要求舊的位置,那麼很可能有一箇舊的位置軸承0.0.0.0被存儲在你的設備上的某個地方,它會給你錯誤的價值。
  4. 此外,您還沒有指定是否要求獲得正確使用GPS所需的權限。

更新: - 至於說通過OP的問題是沒有一個明確的小區接收。一旦在晴朗的天空下,他得到了正確的GPS讀數。

+0

我也嘗試過'onLocationChanged()'函數,但問題仍然存在。 –

+0

請向我們顯示您要求獲取位置的權限。此外,如果可能,請嘗試在其他Android設備上運行您的應用,或者在設備上使用任何其他位置應用(例如谷歌地圖)來檢查您是否獲得了位置信息。 –

+0

刪除上述評論用以下權限更新您的問題。你所要求的權限也沒關係,所以沒問題。 –

相關問題