1.默认gps定位

2.判断gps是否能定位,不能切换到network定位

3.监听gps定位,如果获取到gps信号,停止network定位

import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.List;import java.util.Timer;import java.util.TimerTask;import com.citygis007.appdata.AppData;import com.citygis007.gpsandjz.MainActivity;import com.citygis007.gpsandjz.R;import android.R.integer;import android.R.string;import android.annotation.SuppressLint;import android.app.Service;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.location.Criteria;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.location.LocationProvider;import android.os.Binder;import android.os.Bundle;import android.os.IBinder;import android.telephony.NeighboringCellInfo;import android.telephony.PhoneStateListener;import android.telephony.SignalStrength;import android.telephony.TelephonyManager;import android.telephony.cdma.CdmaCellLocation;import android.telephony.gsm.GsmCellLocation;import android.text.format.Time;import android.util.Log;import android.widget.EditText;import android.widget.Toast;public class WriteLog extends Service {Timer timer=null;boolean isRun=false;private int seconds=30;private boolean isGps=false;private boolean isJizhan=false;private String mfilename="";private TelephonyManager mTelephonyManager;private MyPhoneStateListener phoneStateListener;private LocationManager locationManager;private String provider;private String TAG="WriteLog";private Location location1;private Location currentlocation=null;String log1,log2,log3;@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}// public class MyBinder extends Binder{//        //        public WriteLog getService(){//            return WriteLog.this;//        }//    }//    //    private MyBinder myBinder = new MyBinder();@Overridepublic void onCreate() {// TODO Auto-generated method stubLog.i("service", "onCreate");writeLog(AppData.fileTest, "onCreate\r\n");super.onCreate();SharedPreferences preferences=getApplicationContext().getSharedPreferences(AppData.stringValue, MODE_PRIVATE);SharedPreferences.Editor editor=preferences.edit();mfilename=preferences.getString("filename", MainActivity.filename);editor.putBoolean("isRun", true);editor.commit();locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);//provider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();openGPS();phoneStateListener=new MyPhoneStateListener();}@Overridepublic void onDestroy() {Log.i("service", "onDestroy");writeLog(AppData.fileTest, "onDestroy\r\n");SharedPreferences preferences=getApplicationContext().getSharedPreferences(AppData.stringValue, MODE_PRIVATE);SharedPreferences.Editor editor=preferences.edit();editor.clear();editor.commit();isGps=false;isJizhan=false;if(timer!=null){timer.cancel();timer.purge();}stopGPS();super.onDestroy();}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);//if (locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) //{//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,this);//}//else if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) //{//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,this);//}Log.i("service", "onStart");writeLog(AppData.fileTest, "onStart\r\n");if(intent==null){Log.i("service", "intent null");writeLog(AppData.fileTest, "intent null\r\n");SharedPreferences preferences=getApplicationContext().getSharedPreferences(AppData.stringValue, MODE_PRIVATE);isRun=preferences.getBoolean("isRun", false);isGps=preferences.getBoolean("isGps", false);isJizhan=preferences.getBoolean("isJizhan", false);seconds=preferences.getInt("seconds", 30);//mfilename=preferences.getString("filename", MainActivity.filename);if(isRun){if(timer!=null){timer.cancel();timer.purge();}if(isGps||isJizhan){timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif(isGps||isJizhan){getLacAndGps();//通知Activity  Intent intent = new Intent();  intent.setAction(AppData.LOCATION_ACTION);  intent.putExtra(AppData.LOCATION, log1+log2+log3);  sendBroadcast(intent); }else{this.cancel();}}}, 0, seconds*1000);}}else{stopSelf();}}else{Log.i("service", "intent not null");writeLog(AppData.fileTest, "intent not null\r\n");Bundle bundle=intent.getExtras();isRun=bundle.getBoolean("isRun",false);Log.i("service", "isRun:"+isRun);writeLog(AppData.fileTest,"isRun:"+isRun+"\r\n");if(isRun){if(timer!=null){timer.cancel();timer.purge();}isGps=bundle.getBoolean("isGps", false);isJizhan=bundle.getBoolean("isJizhan", false);seconds=bundle.getInt("seconds", seconds);if(isGps||isJizhan){timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif(isGps||isJizhan){getLacAndGps();//通知Activity  Intent intent = new Intent();  intent.setAction(AppData.LOCATION_ACTION);  intent.putExtra(AppData.LOCATION, log1+log2+log3);  sendBroadcast(intent); }else{this.cancel();}}}, 0, seconds*1000);}}else{stopSelf();}}}class MyPhoneStateListener extends PhoneStateListener{private int lastStrength = 0;public void onSignalStrengthsChanged(SignalStrength signalStrength) {super.onSignalStrengthsChanged(signalStrength);lastStrength = signalStrength.getGsmSignalStrength();}/** 获取上一次变化到现在的信号强度值。 */public int getLastStrength() {return lastStrength;}};public boolean openGPS(){boolean flag=false;if(locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)){//设置监听器,自动更新的最小时间为间隔15秒,最小位移变化超过5米locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);             flag=true;}if(locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)){locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);flag=true;}return flag;}public void stopGPS(){locationManager.removeUpdates(locationListener);}private LocationListener locationListener=new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {// TODO Auto-generated method stub;  //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,networkListener);  // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数  System.out.println(" Provider的转态改变 !");Log.i("provider", "Provider的转态改变 !");Log.i("provider", provider);if (LocationProvider.OUT_OF_SERVICE == status) {             Log.i("provider", "GPS服务丢失,切换至网络定位");           writeLog(AppData.fileTest, provider+"GPS服务丢失,切换至网络定位");        }  }@Overridepublic void onProviderEnabled(String provider) {// TODO Auto-generated method stub// Provider被disable时触发此函数,比如GPS被关闭  System.out.println("GPS被关闭 !");Log.i("provider", "GPS被关闭 !");}@Overridepublic void onProviderDisabled(String provider) {// TODO Auto-generated method stub//  Provider被enable时触发此函数,比如GPS被打开  System.out.println("GPS被关闭 !");Log.i("provider", "GPS被关闭 !");}@Overridepublic void onLocationChanged(Location location) {// TODO Auto-generated method stubcurrentlocation=location;writeLog(AppData.fileTest, location+"");}};private boolean isBetterLocation(Location location,Location currentBestLocation){if (currentBestLocation == null){// A new location is always better than no locationreturn false;}else {return true;}}private boolean isnewLocation(Location lastLocation,Location currentLocation){String a=lastLocation.getProvider();String b=currentLocation.getProvider();if (a==b){return true;}else {return false;}}@SuppressLint("NewApi")public void getLacAndGps(){SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss\r\n");String date=dateFormat.format(new Date());log1=date;//int year=0;//int month=0;//int day=0;//int hour=0;//int minute=0;//int second=0;// Calendar calendar = Calendar.getInstance(); // year=(calendar.get(Calendar.YEAR));// month=(calendar.get(Calendar.MONTH)+1);// day=calendar.get(Calendar.DAY_OF_MONTH);// hour=calendar.get(Calendar.HOUR_OF_DAY);// minute=calendar.get(Calendar.MINUTE);// second=calendar.get(Calendar.SECOND); //         if ((second%5)!=0) {//second=second+(5-(second%5));//}//        String date=year+"-"+month+"-"+day+"  "+hour+":"+minute+":"+second+"\r\n";//         log1=date;//         Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。////         t.setToNow(); // 取得系统时间。//         year =t.year;//          month = t.month;//          day = t.monthDay;//          hour = t.hour; // 0-23//          minute = t.minute;//          second = t.second;//          String m=year+"-"+month+"-"+day+"  "+hour+":"+minute+":"+second+"\r\n";writeLog(AppData.filepath+mfilename+".txt", date);writeLog(AppData.fileLog, date);if(isGps){if (locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {provider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();location1=locationManager.getLastKnownLocation(provider);//boolean mflag=isBetterLocation(location1, currentlocation);//if (mflag) {//location1=currentlocation;//}String a="";String b="";                if (currentlocation!=null) {                 a=currentlocation.getProvider().toString();                 String time=dateFormat.format(new Date(currentlocation.getTime()));}                if (location1!=null) {                 b=location1.getProvider().toString();                 String time1=dateFormat.format(new Date(location1.getTime()));}if (location1==null||currentlocation==null||a.equals("network")){System.out.println("GPS获取坐标失败!");Log.i("service", "GPS获取坐标失败!");writeLog(AppData.fileTest, "GPS获取坐标失败!"+date);if(locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)){provider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER).getName();location1 = locationManager.getLastKnownLocation(provider);if (currentlocation==null) {}else {location1=currentlocation;}System.out.println("网络服务开启!");Log.i("service", "网络服务开启!");writeLog(AppData.fileTest, "网络服务开启!"+date);if(location1  != null)   { System.out.println("网络获取坐标成功!");Log.i("service", "网络获取坐标成功");writeLog(AppData.fileTest, "网络获取坐标成功"+date);writeGPSPoint(location1);}else {System.out.println("网络获取坐标失败!");Log.i("service", "GPS开启,网络服务开启,但是获取坐标失败!");writeLog(AppData.fileTest, "GPS开启,网络服务开启,但是获取坐标失败!"+date);}}else {if (currentlocation==null) {}else {location1=currentlocation;}System.out.println("GPS获取坐标失败!");Log.i("service", "GPS获取坐标失败!");writeLog(AppData.fileTest, "GPS获取坐标失败!"+date);}}else {if (currentlocation==null) {}else {location1=currentlocation;}System.out.println("GPS获取坐标成功!");Log.i("service", "GPS获取坐标成功");writeLog(AppData.fileTest, "GPS获取坐标成功"+date);writeGPSPoint(location1);}}else if(locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)){System.out.println("GPS未开启!网络服务开启!");writeLog(AppData.fileTest, "GPS未开启!网络服务开启!"+date);provider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER).getName();location1 = locationManager.getLastKnownLocation(provider);if (currentlocation==null) {}else {location1=currentlocation;}if(location1  != null)   {  try {writeGPSPoint(location1);} catch (Exception e) {e.printStackTrace();}}else{System.out.println("GPS未开启!网络服务开启!网络获取坐标失败!");Log.i("service", "GPS未开启!网络服务开启!网络获取坐标失败!");writeLog(AppData.fileTest, "GPS未开启!网络服务开启!网络获取坐标失败!"+date);}}else {System.out.println("GPS和网络没有开启!");Log.i("service", "GPS和网络没有开启!");writeLog(AppData.fileTest, "GPS和网络没有开启!"+date);}}if(isJizhan){String operator="";int mcc=0;int mnc=0;int type=0 ;try {mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); type =mTelephonyManager.getNetworkType();mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);operator = mTelephonyManager.getNetworkOperator();  } catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}try {mcc = Integer.parseInt(operator.substring(0, 3));  mnc = Integer.parseInt(operator.substring(3));StringBuffer sb1 = new StringBuffer();int lac=0;int cellId=0;int psc=-1;if(mnc==0||mnc==1){GsmCellLocation location = (GsmCellLocation) mTelephonyManager.getCellLocation();  lac = location.getLac();  cellId = location.getCid();  try {int version = Integer.valueOf(android.os.Build.VERSION.SDK);     if(version  >= 9) {   psc = location.getPsc();}else{psc=-1;}} catch (Exception e) {e.printStackTrace();psc=-1;}sb1.append("移动国家码(MCC) : " + mcc+ "\r\n"); // 取出当前邻区的LAC  sb1.append("移动网络码(MNC) : " + mnc+ "\r\n"); // 取出当前邻区的CID sb1.append("位置区编码(LAC) : " + lac+ "\r\n"); // 取出当前邻区的LAC  sb1.append("手机信号覆盖区域的的编号ID(CID) : " + cellId+ "\r\n"); // 取出当前邻区的CID  sb1.append("网络类型:"+mTelephonyManager.getNetworkType()+ "\r\n");sb1.append("主同步码(PSC):"+psc+ "\r\n");sb1.append("接收信号的强度(RSSI) : " +phoneStateListener.getLastStrength() + "\r\n");Log.i(TAG, sb1.toString());}else if(mnc==2||mnc==3){// 中国电信获取LAC、CID的方式  CdmaCellLocation location1 = (CdmaCellLocation) mTelephonyManager.getCellLocation(); lac = location1.getNetworkId(); cellId = location1.getBaseStationId();psc=location1.getSystemId();//                psc=location1.getsb1.append("移动国家码(MCC) : " + mcc+ "\r\n"); // 取出当前邻区的LAC  sb1.append("移动网络码(MNC) : " + mnc+ "\r\n"); // 取出当前邻区的CID sb1.append("CDMA网络标识号(NID) : " + lac+ "\r\n"); // 取出当前邻区的LAC  sb1.append("CDMA基站识别码(BSID) : " + cellId+ "\r\n"); // 取出当前邻区的CID  sb1.append("网络类型:"+mTelephonyManager.getNetworkType()+ "\r\n");sb1.append("系统识别码(SID):"+psc+ "\r\n");sb1.append("接收信号的强度(RSSI) : " +phoneStateListener.getLastStrength() + "\r\n");Log.i(TAG, sb1.toString());}// 获取邻区基站信息  List infos = mTelephonyManager.getNeighboringCellInfo();StringBuffer sb = new StringBuffer("临近基站总数 : " +infos.size() + "\r\n");  //StringBuffer sb = new StringBuffer();  for (NeighboringCellInfo info1 : infos) { // 根据邻区总数进行循环  sb.append("位置区编码(LAC) : " + info1.getLac()+ "\r\n"); // 取出当前邻区的LAC  sb.append("手机信号覆盖区域的的编号ID(CID) : " + info1.getCid()+ "\r\n"); // 取出当前邻区的CID  sb.append("网络类型:"+info1.getNetworkType()+ "\r\n");sb.append("主同步码(PSC):"+info1.getPsc()+ "\r\n");sb.append("接收信号的强度(RSSI) : " +info1.getRssi() + "\r\n"); // 获取邻区基站信号强度  } //List infos = mTelephonyManager.getAllCellInfo();//StringBuffer sb = new StringBuffer("临近基站总数 : " +infos.size() + "\r\n");  ////StringBuffer sb = new StringBuffer();  //for (CellInfo info1 : infos) { // 根据邻区总数进行循环  //sb.append("位置区编码(LAC) : " + info1.getLac()+ "\r\n"); // 取出当前邻区的LAC  //sb.append("手机信号覆盖区域的的编号ID(CID) : " + info1.getCid()+ "\r\n"); // 取出当前邻区的CID  //sb.append("网络类型:"+info1.getNetworkType()+ "\r\n");//sb.append("主同步码(PSC):"+info1.getPsc()+ "\r\n");//sb.append("接收信号的强度(RSSI) : " +info1.getRssi() + "\r\n"); // 获取邻区基站信号强度  //} Log.i(TAG, " 获取邻区基站信息:" + sb.toString());  writeLog(AppData.fileLog, sb1.toString()+sb.toString());writeLog(AppData.filepath+mfilename+".txt", sb1.toString()+sb.toString());log3=sb1.toString()+sb.toString();} catch (Exception e) {e.printStackTrace();}  }writeLog(AppData.fileLog, "\r\n");//log3="";}private void writeGPSPoint(Location location){if(location!=null){log2="lon:"+location.getLatitude()+" lat:"+location.getLongitude()+"\r\n";writeLog(AppData.fileGps,"lon:"+location.getLatitude()+" lat:"+location.getLongitude()+"\r\n");writeLog(AppData.filepath+mfilename+".txt", "lon:"+location.getLatitude()+" lat:"+location.getLongitude()+"\r\n");Log.i(TAG, "lon:"+location.getLatitude()+" lat:"+location.getLongitude()+"\r\n");}else{writeLog(AppData.fileGps,"lon:"+0.0+" lat:"+0.0+"\r\n");log2="lon:"+0.0+" lat:"+0.0+"\r\n";Log.i(TAG, "lon:"+0.0+" lat:"+0.0+"\r\n");}}/** * 写日志文件 * @param fileName日志文件名 * @param log日志信息 */private void writeLog(String path,String log){if (path==null){path=mfilename;}File file=new File(path);File fileParent=file.getParentFile();fileParent.mkdirs();if (file.exists()) {try {FileWriter fileWriter=new FileWriter(file, true);fileWriter.write(log);fileWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return;}}else {try {file.createNewFile();} catch (IOException e1) {e1.printStackTrace();return;}try {FileWriter fileWriter=new FileWriter(file, true);fileWriter.write(log);fileWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return;}}}}


更多相关文章

  1. Android(安卓)中使用 AsyncTask 异步读取网络图片
  2. Android(安卓)Intent调用 Uri的使用几种格式
  3. Android设置GPS及获取经纬度坐标
  4. Android监听WIFI网络的变化并且获得当前信号强度
  5. JS获取移动端系统信息(操作系统、操作系统版本、横竖屏状态、设
  6. 关于Android(安卓)Https网络连接失败奇葩问题 ExtCertPathValida
  7. Android(安卓)计算两个地理坐标之间的距离
  8. Android(安卓)获取网络状态的工具类
  9. Android(安卓)Intent调用大全

随机推荐

  1. Android 图片压缩
  2. android 进度对话框的使用
  3. BroadcastReceiver广播监听android网络状
  4. Introduction to Android Power Manageme
  5. Android中自定义View支持缩放
  6. android 获取手机系统信息
  7. android 网络图片查看器
  8. Android判断网络是否断开(WIFI 状态)--Conn
  9. Android中让Service被关闭后再重新启动
  10. Android 中Fragment使用