2014-04-07 5 views
-2

나는 이미 질문을 올렸습니다 : How to track GPS If that Reaches particular location or around 20 meters? 그걸로 시작하는 법을 배웠고, 추적 할 코드를 만들었습니다.Android GPS 추적 프로젝트를 디버깅하는 방법은 무엇입니까?

작업 :

import java.text.DecimalFormat; 
import java.text.NumberFormat; 

import android.app.Activity; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.content.SharedPreferences; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class ProxAlertActivity extends Activity { 

    private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in Meters 
    private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000; // in Milliseconds 

    private static final long POINT_RADIUS = 500; // in Meters 
    private static final long PROX_ALERT_EXPIRATION = -1; 

    private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY"; 
    private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY"; 

    private static final String PROX_ALERT_INTENT = "com.javacodegeeks.android.lbs.ProximityAlert"; 

    private static final NumberFormat nf = new DecimalFormat("##.########"); 

    private LocationManager locationManager; 

    private EditText latitudeEditText; 
    private EditText longitudeEditText; 
    private Button findCoordinatesButton; 
    private Button savePointButton; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 

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

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     locationManager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, 
         MINIMUM_TIME_BETWEEN_UPDATE, 
         MINIMUM_DISTANCECHANGE_FOR_UPDATE, 
         new MyLocationListener() 
     ); 

     latitudeEditText = (EditText) findViewById(R.id.point_latitude); 
     latitudeEditText.setText("13.030729"); 

     longitudeEditText = (EditText) findViewById(R.id.point_longitude); 
     longitudeEditText.setText("80.208975"); 

     findCoordinatesButton = (Button) findViewById(R.id.find_coordinates_button); 
     findCoordinatesButton.setVisibility(View.GONE); 

     savePointButton = (Button) findViewById(R.id.save_point_button); 

     findCoordinatesButton.setOnClickListener(new OnClickListener() {    
      @Override 
      public void onClick(View v) { 
       populateCoordinatesFromLastKnownLocation(); 
      } 
     }); 

     savePointButton.setOnClickListener(new OnClickListener() {   
      @Override 
      public void onClick(View v) { 
       saveProximityAlertPoint(); 
      } 
     }); 

    } 

    private void saveProximityAlertPoint() { 
     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (location==null) { 
      Toast.makeText(this, "No last known location. Aborting...", Toast.LENGTH_LONG).show(); 
      return; 
     } 
     saveCoordinatesInPreferences((float)location.getLatitude(), (float)location.getLongitude()); 
     addProximityAlert(location.getLatitude(), location.getLongitude()); 

    } 

    private void addProximityAlert(double latitude, double longitude) { 

     Intent intent = new Intent(PROX_ALERT_INTENT); 
     PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0); 

     locationManager.addProximityAlert(
      latitude, // the latitude of the central point of the alert region 
      longitude, // the longitude of the central point of the alert region 
      POINT_RADIUS, // the radius of the central point of the alert region, in meters 
      PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration 
      proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected 
     ); 

     IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT); 
     registerReceiver(new ProximityIntentReceiver(), filter); 

    } 

    private void populateCoordinatesFromLastKnownLocation() { 
     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (location!=null) { 
      latitudeEditText.setText(nf.format(location.getLatitude())); 
      longitudeEditText.setText(nf.format(location.getLongitude())); 
     } 
    } 

    private void saveCoordinatesInPreferences(float latitude, float longitude) { 
     SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE); 
     SharedPreferences.Editor prefsEditor = prefs.edit(); 
     prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude); 
     prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude); 
     prefsEditor.commit(); 
    } 

    private Location retrievelocationFromPreferences() { 
     SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE); 
     Location location = new Location("POINT_LOCATION"); 
     location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY, 0)); 
     location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY, 0)); 
     return location; 
    } 

    public class MyLocationListener implements LocationListener { 
     public void onLocationChanged(Location location) { 
      Location pointLocation = retrievelocationFromPreferences(); 
      float distance = location.distanceTo(pointLocation); 
      Toast.makeText(ProxAlertActivity.this, 
        "Distance from Point:"+distance, Toast.LENGTH_SHORT).show(); 

     } 
     public void onStatusChanged(String s, int i, Bundle b) {    
     } 
     public void onProviderDisabled(String s) { 
     } 
     public void onProviderEnabled(String s) {   
     } 
    } 

} 

방송 :

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.graphics.Color; 
import android.location.LocationManager; 
import android.util.Log; 

public class ProximityIntentReceiver extends BroadcastReceiver { 

    private static final int NOTIFICATION_ID = 1000; 

    @SuppressWarnings("deprecation") 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     String key = LocationManager.KEY_PROXIMITY_ENTERING; 

     Boolean entering = intent.getBooleanExtra(key, false); 

     if (entering) { 
      Log.d(getClass().getSimpleName(), "entering"); 
     } 
     else { 
      Log.d(getClass().getSimpleName(), "exiting"); 
     } 

     NotificationManager notificationManager = 
      (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

     PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, null, 0);  

     Notification notification = createNotification(); 
     notification.setLatestEventInfo(context, "Proximity Alert!", "You are near your point of interest.", pendingIntent); 

     notificationManager.notify(NOTIFICATION_ID, notification); 

    } 

    private Notification createNotification() { 
     Notification notification = new Notification(); 

     notification.icon = R.drawable.ic_menu_notifications; 
     notification.when = System.currentTimeMillis(); 

     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.flags |= Notification.FLAG_SHOW_LIGHTS; 

     notification.defaults |= Notification.DEFAULT_VIBRATE; 
     notification.defaults |= Notification.DEFAULT_LIGHTS; 

     notification.ledARGB = Color.WHITE; 
     notification.ledOnMS = 1500; 
     notification.ledOffMS = 1500; 

     return notification; 
    } 

} 

매니페스트 :

<?xml version="1.0" encoding="utf-8"?> 

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="com.javacodegeeks.android.lbs" 
     android:versionCode="1" 
     android:versionName="1.0"> 

    <application android:icon="@drawable/icon" android:label="@string/app_name"> 

     <activity android:name=".ProxAlertActivity" 
        android:label="MyTrack"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity>  

    </application> 

    <uses-sdk android:minSdkVersion="3" /> 

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.VIBRATE" /> 

</manifest> 

는 I가 500m 반경에 입력하여, 그으로 고정 위치를주고, 그것을 짐작 경고를받을 것입니다. 이것을 시작한 후에, 나는 1000 미터 이상 가고 가고 돌려 보내기 시작했다.

하지만 내 자리에 도착하기 전까지는 아무런주의를 기울이지 않았습니다.

+0

왜 방송 수신기가 필요하십니까? onLocationChanged()의 정적 인 위치와 현재의 위치를 ​​간단하게 비교할 수있다. 그리고 업데이트 간격을 충분히 작게 설정하여 경로를 볼 수 있습니다. – mangusta

+0

추적 할 필요가 있습니다. 지정된 500 미터 반경 범위에 도달하면 경보 orsomething을 가져올 필요가 있습니다. – kathir

+0

그래서 문제가 무엇입니까? 현재 위치가'onLocationChanged()'에 주어진 점으로부터 500 미터 범위에 있는지 확인하십시오. 경고 또는 알림 또는 토스트 또는 무엇이든간에 – mangusta

답변

0

Google 서비스 위치 API를 사용하여 위치 정보를 가져옵니다. 때때로 LocationManager 클래스는 위치를 제공하는 동안 문제를 만듭니다. 코드는 아래에 간다

..

는 매니페스트 파일에서 응용 프로그램 태그 아래에 다음 코드

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" /> 

추가 ..

<meta-data 
android:name="com.google.android.gms.version" 
android:value="@integer/google_play_services_version" /> 

자바 코드가 여기에 표시됩니다 .. 매니페스트에 이러한 권한을 추가합니다. .

package com.example.location_test; 

import android.app.Activity; 

import android.location.Location; 
import android.os.Bundle; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesClient; 
import com.google.android.gms.location.LocationClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 

public class Activity1 extends Activity implements 
     GooglePlayServicesClient.ConnectionCallbacks, 
     GooglePlayServicesClient.OnConnectionFailedListener, LocationListener { 

    EditText e1, e2; 
    Button b; 
    LocationClient mLocationClient; 
    Location mCurrentLocation; 
    LocationRequest mLocationRequest; 

    // Milliseconds per second 
    private static final int MILLISECONDS_PER_SECOND = 1000; 
    // Update frequency in seconds 
    public static final int UPDATE_INTERVAL_IN_SECONDS = 5; 
    // Update frequency in milliseconds 
    private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND 
      * UPDATE_INTERVAL_IN_SECONDS; 
    // The fastest update frequency, in seconds 
    private static final int FASTEST_INTERVAL_IN_SECONDS = 1; 
    // A fast frequency ceiling in milliseconds 
    private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND 
      * FASTEST_INTERVAL_IN_SECONDS; 
    private static final String PROVIDER = "flp"; 
    private static final float ACCURACY = 3.0f; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity1); 

     b = (Button) findViewById(R.id.b); 
     e1 = (EditText) findViewById(R.id.e1); 
     e2 = (EditText) findViewById(R.id.e2); 

     try { 
      // Create the LocationRequest object 
      mLocationRequest = LocationRequest.create(); 
      // Use high accuracy 
      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
      // Set the update interval to 5 seconds 
      mLocationRequest.setInterval(UPDATE_INTERVAL); 
      // Set the fastest update interval to 1 second 
      mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 

      mLocationClient = new LocationClient(Activity1.this, 
        Activity1.this, Activity1.this); 
      mLocationClient.connect(); 
      // mLocationClient.setMockMode(true); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult arg0) { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "Connection Failed.", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onConnected(Bundle arg0) { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 
     mLocationClient.requestLocationUpdates(mLocationRequest, this); 
    } 

    @Override 
    public void onDisconnected() { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "Connection Disconnected.", Toast.LENGTH_SHORT) 
       .show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     String msg = "Updated Location: " 
       + Double.toString(location.getLatitude()) + "," 
       + Double.toString(location.getLongitude()); 
     Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 
    } 
} 
+0

Hav 링크 또는 샘플. 나는 이미 어딘가에 stackoverflow 어딘가에 대한 GPS를 추적 서핑에 대한 답변을 발견. 당신이 그렇게한다면 더 설명해 주면 더 좋을 것입니다. – kathir

+0

코드로 위의 대답을 편집했습니다. 체크 아웃하십시오 .. 필요한 곳에서 코드를 수정하십시오 .. –

+0

위 코드는 현재 위치를 찾는 코드입니다. 내 퀴 스턴을 올바르게 받고 있니? ? 내가 설명하자면, 나는 이미 하나의 위치를 ​​저장하고, htat cse에서 500m의 위치 반경에 들어가면 나에게 경고해야한다 ... 나는 현재 GPS 위치를 가져 오는 법을 알고, 나의 qus는 내가 입력했는지를 추적하는 것이다. 내 지정된 위치로., ... – kathir

관련 문제