2014年6月9日 星期一

Android GPS 定位 距離 偵測

開車照相偵測app都會偵測某個點有照相偵測機,然後發出警告,此app會用到GPS與Broadcast功能。需建立GPSService.java與GPSReceiver.java檔(與MainActivity.java同資料夾)
1.activity_main.xml
輸入接近目標的經緯度,打勾啟動

  
   
  
  
  
  

2.AndroidManifest.xml
加入GPSReceiver接收功能與GPSService廣播功能,VIBRATE手機震動功能,ACCESS_FINE_LOCATION定位功能。



        
            
                
            
        

        
3.MainActivity.java
 private EditText lat, lon;
 private CheckBox checkBox_service;
 private TextView output;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  lat = (EditText) findViewById(R.id.txtLat);
  lon = (EditText) findViewById(R.id.txtLong);
  checkBox_service = (CheckBox) findViewById(R.id.checkBox_service);
  output = (TextView) findViewById(R.id.output);
  if (checkBox_service.isChecked()) {
   start_Click(); //啟動功能
  } else {
   stop_Click(); //停止功能
  }
 }
 public void start_Click() {
  float latitude = Float.parseFloat(lat.getText().toString()); //取得輸入座標
  float longitude = Float.parseFloat(lon.getText().toString()); //取得輸入座標
  Intent intent = new Intent(this, GPSService.class); //送至GPSService.java
  intent.putExtra("LATITUDE", latitude); //發送座標至GPSService
  intent.putExtra("LONGITUDE", longitude); //發送座標至GPSService
  startService(intent);
  output.setText("服務啟動中");
 }

 public void stop_Click() {
  Intent intent = new Intent(this, GPSService.class);
  stopService(intent);
  output.setText("服務停止中");
 }
4.GPSService.java
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSService extends Service implements LocationListener {
 private LocationManager manager;
 private boolean isInArea;
 private double latitude, longitude;

 @Override
 public void onCreate() {

  manager = (LocationManager) getSystemService(LOCATION_SERVICE);
  manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 1,
    this);
  manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1,
    this);
  isInArea = false; //是否在範圍內
 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  try {
   latitude = (double) intent.getFloatExtra("LATITUDE1", 22.6297370f); //取得座標
   longitude = (double) intent.getFloatExtra("LONGITUDE1", 120.3278820f); //取得座標
  } catch (NullPointerException e) {
   Log.i("GPSService","NullPointException");
  }
  Log.d("GPSService", "lat/long: " + latitude + ": " + longitude);
  return START_STICKY;
 }

 @Override
 public void onDestroy() {
  manager.removeUpdates(this); //移除定位服務更新
 }

 @Override
 public void onLocationChanged(Location current) {
  // TODO Auto-generated method stub
  if (current == null)
   return;
  Location dest = new Location(current); //取得現在位置
  dest.setLatitude(latitude); //取得現在位置座標
  dest.setLongitude(longitude); //取得現在位置座標
  float distance = current.distanceTo(dest); //計算目標位置與現在位置距離
  if (distance < 1000.0) { //當目標小於1公里時
   if (isInArea == false) { //在區域內
    Intent intent = new Intent("android.broadcast.LOCATION"); //啟動廣播服務
    sendBroadcast(intent); //發送廣播
    isInArea = true; //是否在區域內:true
   }
  } else {
   isInArea = false; //是否在區域內:false
  }

 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onProviderEnabled(String provider) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onProviderDisabled(String provider) {
  // TODO Auto-generated method stub

 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }

}

5.GPSReceiver.java
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.os.Vibrator;

public class GPSReceiver extends BroadcastReceiver {
 static int id = 70000;
 @SuppressWarnings("deprecation")
 @Override
 public void onReceive(Context context, Intent intent) {
  //Notification
  NotificationManager notificationManager = (NotificationManager) context
    .getSystemService(android.content.Context.NOTIFICATION_SERVICE);

  Notification notification = new Notification(R.drawable.ic_launcher,
    "您已經接近目標", System.currentTimeMillis()); //跳出Notification訊息
  Intent newintent = new Intent(context, MainActivity.class);
  PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
    newintent, 0);
  notification.setLatestEventInfo(context, "再接近就要被拍了!!", null, contentIntent);

  notificationManager.notify(id++, notification);
  
  //手機震動
  Vibrator vibrator = (Vibrator) context
    .getSystemService(Context.VIBRATOR_SERVICE);
  vibrator.vibrate(500); // 半秒
 }
}

參考來源:
http://goo.gl/BbbtPe
http://hscc.cs.nctu.edu.tw/~lincyu/Android/Chapter7.pdf

沒有留言 :

張貼留言