2016-10-04 2 views
-1

GPS 및 기타 센서의 데이터를 읽고 파일에 기록하고 싶습니다. 나는 가속도계를 위해 그것을 할 수 있지만 안드로이드를 처음 접했을 때 GPS를위한 부분을 구현할 수 없었다. 이 작업을 수행하는 방법을 간단히 설명하십시오. 다음은 내가 가지고있는 코드입니다.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

로컬 서비스 내에 센서 및 위치 기록을 고려해보십시오. 귀하의 UI 활동의 라이프 사이클과는 별도로 수명주기가 있습니다. 서비스를 바인딩 할 때 제어됩니다. 또한 데이터 버퍼링 된 출력 스트림 클래스를 사용하여 모든 센서 또는 위치 이벤트를 신속하게 처리 할 수 ​​있습니다. 하드웨어에서 오는 이벤트에 대한 버퍼 제한으로 인해 리스너에서 많은 프로세스를 수행하지 않는 것이 중요합니다. 또한 위치 서비스에 대한 권한에 대해 Android 매니페스트를 처리해야합니다. 위치 권한은 Google에서 위험한 것으로 간주되므로 보안 예외를 추가하거나 사용자가 위험한 권한을 처리해야합니다. 또한 구성 조정과 GPS 공급자 간의 호환성을 보장하기 위해 ubication 서비스에 대한 사용자 구성을 확인해야합니다.

관련 문제