2016-10-04 83 views
-1

我希望從GPS和其他傳感器讀取數據並將其寫入文件。我能夠做到這一點的加速度計,但不能夠實現GPS的部分,因爲我是新來的android。請以簡單的步驟解釋我如何做到這一點。這裏是我有的代碼:將GPS數據保存到Android中的文件

import android.Manifest; 
import android.content.Context; 
import android.content.pm.PackageManager; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.net.Uri; 
import android.os.Environment; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gms.appindexing.Action; 
import com.google.android.gms.appindexing.AppIndex; 
import com.google.android.gms.appindexing.Thing; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.opencsv.CSVWriter; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 

public class MainActivity extends AppCompatActivity implements SensorEventListener { 

    private SensorManager mSensorManager; 
    private Sensor mSensor; 
    private static String TAG = "PermissionDemo"; 
    private static final int REQUEST_WRITE_STORAGE = 112; 

    TextView xval; 
    TextView yval; 
    TextView zval; 
    TextView av; 
    float axisX; 
    float axisY; 
    float axisZ; 
    float gyX; 
    float gyY; 
    float gyZ; 
    TextView gxval; 
    TextView gyval; 
    TextView gzval; 
    int click = 0; 
    String entry = ""; 
    String Gyentry = ""; 

    //GPS 
    protected String mLatitudeLabel; 
    protected String mLongitudeLabel; 
    protected TextView mLatitudeText; 
    protected TextView mLongitudeText; 

    LocationManager mLocationManager; 
    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    private GoogleApiClient client; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 
     mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
     //Toast.makeText(getApplicationContext(),"ACTIVITY SENSING PROJECT", Toast.LENGTH_LONG).show(); 

     xval = (TextView) findViewById(R.id.tv1); 
     yval = (TextView) findViewById(R.id.tv2); 
     zval = (TextView) findViewById(R.id.tv3); 
     gxval = (TextView) findViewById(R.id.tv4); 
     gyval = (TextView) findViewById(R.id.tv5); 
     gzval = (TextView) findViewById(R.id.tv6); 
     av = (TextView) findViewById(R.id.addressview); 
     av.setText("File Path will be displayed here."); 
     //GPS 
     mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     mSensorManager.registerListener(this, mSensor, 2000000000); 
     mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), 5 * 60 * 1000); 
     mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); 
    } 

    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    public Action getIndexApiAction() { 
     Thing object = new Thing.Builder() 
       .setName("Main Page") // TODO: Define a title for the content shown. 
       // TODO: Make sure this auto-generated URL is correct. 
       .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) 
       .build(); 
     return new Action.Builder(Action.TYPE_VIEW) 
       .setObject(object) 
       .setActionStatus(Action.STATUS_TYPE_COMPLETED) 
       .build(); 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client.connect(); 
     AppIndex.AppIndexApi.start(client, getIndexApiAction()); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     AppIndex.AppIndexApi.end(client, getIndexApiAction()); 
     client.disconnect(); 
    } 

    public class LocationListener implements android.location.LocationListener { 
     final String LOG_LABEL = "Location Listener>>"; 

     @Override 
     public void onLocationChanged(Location location) { 
      Log.d(TAG, LOG_LABEL + "Location Changed"); 
      if (location != null) { 
       double longitude = location.getLongitude(); 
       Log.d(TAG, LOG_LABEL + "Longitude:" + longitude); 
       Toast.makeText(getApplicationContext(), "Long::" + longitude, Toast.LENGTH_SHORT).show(); 
       double latitude = location.getLatitude(); 
       Toast.makeText(getApplicationContext(), "Lat::" + latitude, Toast.LENGTH_SHORT).show(); 
       Log.d(TAG, LOG_LABEL + "Latitude:" + latitude); 

      } 
     } 

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

     } 

     @Override 
     public void onProviderEnabled(String provider) { 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 

     } 
    } 

     @Override 
     public void onSensorChanged(SensorEvent event) { 
      if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { 
       return; 
      } 
      Sensor sensor = event.sensor; 
      if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
       axisX = event.values[0]; 
       axisY = event.values[1]; 
       axisZ = event.values[2]; 

       //Log.d(Float.toString(axisX),"yes"); 
       xval.setText("X : " + Float.toString(axisX)); 
       yval.setText("Y : " + Float.toString(axisY)); 
       zval.setText("Z : " + Float.toString(axisZ)); 

       if (click == 1) { 
        Log.d("starting data entry", "Accelerometer Sensor"); 
        entry = entry + Float.toString(axisX) + "," + Float.toString(axisY) + "," + Float.toString(axisZ) + "\n"; 
        //Log.d("entry ", entry); 
        try { 
         accWriteTOCSV(Float.toString(axisX), Float.toString(axisY), Float.toString(axisZ)); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

       } 

      } else if (sensor.getType() == Sensor.TYPE_GYROSCOPE) { 

       gyX = event.values[0]; 
       gyY = event.values[1]; 
       gyZ = event.values[2]; 

       gxval.setText("X : " + Float.toString(gyX)); 
       gyval.setText("Y : " + Float.toString(gyY)); 
       gzval.setText("Z : " + Float.toString(gyZ)); 
       if (click == 1) { 
        Log.d("starting data entry", "Gyroscope Sensor"); 
        Gyentry = Gyentry + Float.toString(gyX) + "," + Float.toString(gyZ) + "," + Float.toString(gyZ) + "\n"; 
        //Log.d("entry ", entry); 
        try { 
         gyroWriteToCSV(Float.toString(gyX), Float.toString(gyY), Float.toString(gyZ)); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 

      } 
      //Toast.makeText(getApplicationContext(), "hey", Toast.LENGTH_LONG).show(); 


     } 

     @Override 
     public void onAccuracyChanged(Sensor sensor, int accuracy) { 

     } 

     /* 
      @Override 
      public void onAccuracyChanged(Sensor sensor, int accuracy) { 
      } 
     */ 
     public void onclickstart(View v) throws IOException { 
      Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show(); 
      click = 1; 
      //file handling put here 
     } 

     public void onclickstop(View v) throws IOException { 
      click = 0; 
      Toast.makeText(getApplicationContext(), "Recording stopped", Toast.LENGTH_LONG).show(); 
      //mSensorManager.unregisterListener(this); 
      //super.onStop(); 
     } 

     public void gyroWriteToCSV(String x, String y, String z) throws IOException { 
      Calendar c = Calendar.getInstance(); 
      File folder = new File(Environment.getExternalStorageDirectory() + "/activitySensing"); 
      boolean success = true; 
      if (!folder.exists()) { 
       success = folder.mkdir(); 
      } 

      if (success) { 
       String dataEntry = folder + "/gyroSensor.csv"; 
       try { 
        FileWriter file_writer = new FileWriter(dataEntry, true); 
        String data = c.get(Calendar.MONTH) + ";" + c.get(Calendar.DATE) + ";" + c.get(Calendar.HOUR) + ";" + c.get(Calendar.MINUTE) + ";" + x + ";" + y + ";" + z + "\n"; 
        file_writer.append(data); 
        file_writer.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     public void accWriteTOCSV(String x, String y, String z) throws IOException { 
      Calendar c = Calendar.getInstance(); 
      File folder = new File(Environment.getExternalStorageDirectory() + "/activitySensing"); 
      boolean success = true; 
      if (!folder.exists()) { 
       success = folder.mkdir(); 
      } 

      if (success) { 
       String dataEntry = folder + "/accSensor.csv"; 
       try { 
        FileWriter file_writer = new FileWriter(dataEntry, true); 
        String data = c.get(Calendar.MONTH) + ";" + c.get(Calendar.DATE) + ";" + c.get(Calendar.HOUR) + ";" + c.get(Calendar.MINUTE) + ";" + x + ";" + y + ";" + z + "\n"; 
        file_writer.append(data); 
        file_writer.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

      private class MyLocationListener implements LocationListener { 
       @Override 
       public void onLocationChanged(Location loc) { 

        Toast.makeText(getBaseContext(), "Location changed : Lat: " + 
            loc.getLatitude() + " Lng: " + loc.getLongitude(), 
          Toast.LENGTH_SHORT).show(); 
        String longitude = "Longitude: " + loc.getLongitude(); 
        Log.v(TAG, longitude); 
        String latitude = "Latitude: " + loc.getLatitude(); 
        Log.v(TAG, latitude); 

        String s = longitude + "\n" + latitude; 
       } 

       @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 
       } 
      } 
    /*@Override 
    public void onSensorChanged(SensorEvent event) { 

    } 

    @Override 
    public void onAccuracyChanged(Sensor sensor, int accuracy) { 

    }*/ 
     } 
    } 

回答

0

你應該考慮做一個本地服務內的傳感器和位置記錄。其生命週期與您的用戶體驗活動的生命週期不同。 當您進行服務綁定時,它會被控制。並使用數據緩衝輸出流類來快速處理每個傳感器或位置事件。由於緩衝區限制了來自硬件的事件,因此重要的是不要在偵聽器中執行很多過程。 您還必須處理Android清單以獲取位置服務的權限。 Google認爲位置權限很危險,因此您必須添加安全例外或處理用戶危險權限。您將不得不檢查用戶配置服務以確保配置調整和GPS提供商之間的兼容性。