2015-08-08 113 views
0

我試圖在我的應用程序中打印緯度和經度以及加速計讀數。但是,當我嘗試從我的主Activity類中的GPS類使用經度和緯度時,它始終返回null。有人能告訴我我做錯了什麼嗎?我已經嘗試過無數種不同的方法(互聯網充滿了它們),但似乎沒有任何辦法可以解決我的問題。謝謝。經度和緯度返回無效

MainActivity.java

package com.explorer.extractor; 

//import packages 

import android.content.Context; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TableLayout; 

import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.util.Calendar; 


public class MainActivity extends ActionBarActivity implements SensorEventListener,OnClickListener { 

    GPSTracker gps; 

    Button button1; 
    Button button2; 

    private SensorManager mSensorManager; 
    Sensor accelerometer; 

    private static final String TAG = MainActivity.class.getName(); 

    private static final String FILENAME = "newgps.txt"; //file where data is written 


    //layout variables 
    TableLayout t1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //initialize sensor manager 
     mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 
     //initialize accelerometer 
     accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
     //mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST); 

     t1 = (TableLayout) findViewById(R.id.main_table); 
     button1 = (Button) findViewById(R.id.button1); 
     button2 = (Button) findViewById(R.id.button2); 

     button1.setOnClickListener(this); 
     button2.setOnClickListener(this); 
    } 

    public void onAccuracyChanged(Sensor sensor, int accuracy){} 

    /**onResume() registers the accelerometer for listening 
    * to the events 
    */ 
    /* 
    protected void onResume(){ 
     super.onResume(); 
     mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST); 
    } 
    */ 
    /* 
    protected void onPause(){ 
     super.onPause(); 
     mSensorManager.unregisterListener(this); 
    } 
    */ 

    public void onSensorChanged(SensorEvent event){ 
     //if sensor status result is unreliable return 
     if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE){ 
      return; 
     } 

     Sensor sensor = event.sensor; 

     //check sensor type 
     if (sensor.getType() == Sensor.TYPE_ACCELEROMETER){ 
      //assign directions 
      float x = event.values[0]; 
      float y = event.values[1]; 
      float z = event.values[2]; 

      try { 
       //write to text file the x, y, and z values each type a sensor detects change 
       writeToFile(Float.toString(x), Float.toString(y), Float.toString(z)); 
       Log.i("LIMA", "hey lily it got here!"); 

       /* 
       String textFromFileString = readFromFile(); 
       TableRow tr = new TableRow(this); 
       if(count%2!=0) { 
        tr.setBackgroundColor(Color.GRAY); 
       } 
       tr.setId(100 + count); 
       tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); 

       //show data read from file 
       dataReading = new TextView(this); 
       dataReading.setId(200 + count); 
       dataReading.setText(textFromFileString); 
       dataReading.setPadding(2, 0, 5, 0); 
       dataReading.setTextColor(Color.WHITE); 
       tr.addView(dataReading); 
       //finally add data to table row 
       t1.addView(tr, new TableLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT)); 
       count++; 
       Log.i("LIMA","Add row. There are now " + t1.getChildCount()+"rows"); 
       */ 
      }catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    } 

    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.button1: 
       mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST); 
       Log.i("LIME","I pressed start!!!"); 
       break; 
      case R.id.button2: 
       mSensorManager.unregisterListener(this); 
       //gps.stopUsingGPS(); 
       Log.i("LIME","I pressed stop!!!"); 
     } 
    } 

    /** 
    * writeToFile: writes data recordings of accelerometer to text file 
    * @param x 
    * @param y 
    * @param z 
    * @throws IOException 
    */ 
    void writeToFile(String x, String y, String z) throws IOException { 

     double latVal; 
     double longVal; 

     String s; 

     //get exact instance of time in which call to write is being made 
     Calendar c = Calendar.getInstance(); 
     //create string to print to text using values in parameter. 
     GPSTracker track = new GPSTracker(this); 
     latVal = track.getLatitude(); 
     Log.i("test", "this is the latitude" + latVal); 
     longVal = track.getLongitude(); 
     s = "Time: " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) + ":" + c.get(Calendar.MILLISECOND) + " Coordinates: " + "x: " + x + " y: " + y + " z: " + z + " Latitude: " + latVal + " Longitude: " + longVal + "\n\r"; 

      //s = "Time: " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) + ":" + c.get(Calendar.MILLISECOND) + " Coordinates: " + "x: " + x + " y: " + y + " z: " + z + "\n\r"; 
      //Log.i("shucks", "it never got the gps."); 



     try { 
      //append new string to file 
      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND | Context.MODE_WORLD_READABLE); 
      //FileWriter fstream = new FileWriter(file, true); 
      //BufferedWriter bw = new BufferedWriter(fstream); 
      OutputStreamWriter bw = new OutputStreamWriter(fos); 
      bw.append(s); 
      bw.append("\n\r"); 
      bw.close(); 
      Log.i("LIMA","IT GOT HERE 2"); 
     } catch(IOException e) { 
      Log.e(TAG, "File write failed: " + e.toString()); 
     } 
    } 

    /** 
    private String readFromFile(){ 
     String ret = ""; 
     try { 
      //open text file to read from 
      InputStream inputStream = openFileInput(FILENAME); 
      if (inputStream != null) { 
       InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
       BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
       String receiveString = ""; 
       StringBuilder stringBuilder = new StringBuilder(); 

       while ((receiveString = bufferedReader.readLine()) != null) { 
        //continue appending to stringBuilder until you've reached the end of file 
        stringBuilder.append(receiveString); 
       } 
       inputStream.close(); 
       ret = stringBuilder.toString(); 
      } 
     } catch (FileNotFoundException e) { 
      Log.e(TAG, "File not found: " + e.toString()); 
     } catch (IOException e) { 
      Log.e(TAG, "Can not read file: " + e.toString()); 
     } 
     return ret; 
    } 
    */ 
} 

GPSTracker.java

package com.explorer.extractor; 

import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 

public class GPSTracker extends Service implements LocationListener { 

    // saving the context for later use 
    public final Context mContext; 

    // if GPS is enabled 
    boolean isGPSEnabled = false; 
    // if Network is enabled 
    boolean isNetworkEnabled = false; 
    // if Location co-ordinates are available using GPS or Network 
    public boolean isLocationAvailable = false; 

    // Location and co-ordinates coordinates 
    Location mLocation; 
    double mLatitude; 
    double mLongitude; 

    // Minimum time fluctuation for next update (in milliseconds) 
    private static final long TIME = 0; 
    // Minimum distance fluctuation for next update (in meters) 
    private static final long DISTANCE = 0; 

    // Declaring a Location Manager 
    public LocationManager mLocationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     mLocationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

    } 

    /** 
    * Returs the Location 
    * 
    * @return Location or null if no location is found 
    */ 
    public Location getLocation() { 
     try { 

      // Getting GPS status 
      isGPSEnabled = mLocationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 


      // If we are reaching this part, it means GPS was not able to fetch 
      // any location 
      // Getting network status 
      isNetworkEnabled = mLocationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (isNetworkEnabled) { 
       mLocationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
         isLocationAvailable = true; // setting a flag that 
         // location is available 
         return mLocation; 
        } 
       } 
      } 
      // If reaching here means, we were not able to get location neither 
      // from GPS not Network, 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     // if reaching here means, location was not available, so setting the 
     // flag as false 
     isLocationAvailable = false; 
     return null; 
    } 

    /** 
    * get latitude 
    * 
    * @return latitude in double 
    */ 
    public double getLatitude() { 
     if (mLocation != null) { 
      mLatitude = mLocation.getLatitude(); 
     } 
     return mLatitude; 
    } 

    /** 
    * get longitude 
    * 
    * @return longitude in double 
    */ 
    public double getLongitude() { 
     if (mLocation != null) { 
      mLongitude = mLocation.getLongitude(); 
     } 
     return mLongitude; 
    } 

    /** 
    * close GPS to save battery 
    */ 
    public void closeGPS() { 
     if (mLocationManager != null) { 
      mLocationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    /** 
    * Updating the location when location changes 
    */ 
    @Override 
    public void onLocationChanged(Location location) { 
     mLatitude = location.getLatitude(); 
     mLongitude = location.getLongitude(); 
    } 

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

} 

回答

1

你是否宣告您的清單此權限嗎?

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 
+0

是的,我包括<用途的許可機器人:名稱= 「android.permission.ACCESS_FINE_LOCATION」/> <使用的許可機器人:名稱= 「android.permission.INTERNET對」/> – CompSci1234