2016-10-04 6 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 считаются опасными, поэтому вам придется добавлять исключения безопасности или разрешать пользователям опасные разрешения. И вам нужно будет проверить конфигурацию пользователя для служб ubication, чтобы обеспечить совместимость между настройкой конфигурации и поставщиком GPS.

 Смежные вопросы

  • Нет связанных вопросов^_^