2016-10-04 3 views
-1

Ich möchte Daten von GPS und anderen Sensoren lesen und in eine Datei schreiben. Ich kann es für Beschleunigungsmesser tun, aber nicht in der Lage, das Teil für GPS zu implementieren, da ich neu bei Android bin. Bitte erläutern Sie mir in einfachen Schritten, wie Sie dies erreichen können. Hier ist ein Code, den ich habe:Speichern GPS-Daten in Datei in 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) { 

    }*/ 
     } 
    } 

Antwort

0

Sie sollten in Betracht ziehen, die Sensor- und Standortaufzeichnung in einem lokalen Dienst zu tun. Mit seinem Lebenszyklus getrennt vom Lebenszyklus Ihrer ui Aktivitäten. Das wird gesteuert, wenn Sie die Service-Bindung vornehmen. Verwenden Sie datengepufferte Ausgabestream-Klassen, um alle Sensor- oder Standortereignisse schnell zu verarbeiten. Es ist wichtig, wegen der Pufferbeschränkung für Ereignisse, die von der Hardware kommen, in Zuhörern nicht viel zu verarbeiten. Sie müssen auch mit Android-Manifest für Berechtigungen für Standortdienste befassen. Standortberechtigungen werden von Google als gefährlich eingestuft. Daher müssen Sie Sicherheitsausnahmen hinzufügen oder gefährliche Benutzerberechtigungen bearbeiten. Außerdem müssen Sie die Benutzerkonfiguration für die Ubication-Dienste überprüfen, um die Kompatibilität zwischen der Konfigurationsanpassung und dem GPS-Anbieter sicherzustellen.

Verwandte Themen