android应用程序在android 2.3.3中运行良好,但在android 4.1.2中停止

android应用程序在android 2.3.3中运行良好,但在android 4.1.2中停止,android,gps,Android,Gps,我的是安卓追踪应用。它获取gps位置并将其发送到服务器。如果找不到gps位置,它将使用手机id获取位置。它在android 2.3.3中运行良好。它也适用于android 4.1.2,但在一段时间后(2小时或8小时,有时1天)停止,没有任何强制关闭消息。 我在谷歌上搜索了一下,但没有找到错误。2.3.3中是否有不推荐的方法。 下面是我的代码。该服务由BroadcastReceiver反复启动,该接收器由AlarmManager启动 我已经在我的清单文件中写了这个: <uses-sdk an

我的是安卓追踪应用。它获取gps位置并将其发送到服务器。如果找不到gps位置,它将使用手机id获取位置。它在android 2.3.3中运行良好。它也适用于android 4.1.2,但在一段时间后(2小时或8小时,有时1天)停止,没有任何强制关闭消息。 我在谷歌上搜索了一下,但没有找到错误。2.3.3中是否有不推荐的方法。 下面是我的代码。该服务由
BroadcastReceiver
反复启动,该接收器由
AlarmManager
启动
我已经在我的清单文件中写了这个:

<uses-sdk android:minSdkVersion="7" 
    android:targetSdkVersion="18"/>
public class GPSLoggerService extends Service implements LocationListener {
    @Override
    public void onCreate() {
        AppLog.logString("GPSLoggerService.onCreate().");
        final SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        AppLog.logString("GPSLoggerService.onCreate().");
        data_mode = settings.getInt("data_mode", 1);
        boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);

        settings.edit().putBoolean("justBooted", false);

        super.onCreate();
        // db = new DBAdapter(this);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        appendLog("in onStartCommend, ");
        AppLog.logString("GPSLoggerService.onStartCommand().");
        this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        startLoggingService();
        startMonitoringTimer();
        try {
            sendData();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // dbadapter = new DBAdapter(this);

        return Service.START_STICKY;
    }

    @Override
    public void onLocationChanged(Location location) {
        appendLog("onLocationChanged, ");
        AppLog.logString("GPSLoggerService.onLocationChanged().");
        didFindLocation = true;
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        altitude = location.getAltitude();
        // Toast.makeText(getApplicationContext(),"lat :"+latitude+"longi :"+longitude,
        // Toast.LENGTH_LONG).show();
        gpsaltitude = String.valueOf(altitude);
        gpslatitude = String.valueOf(latitude);
        gpslongitude = String.valueOf(longitude);
        mps = location.getSpeed();
        kmh = (float) (mps * 3.6);
        speed = Float.toString(kmh);

        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datetime = sdfDateTime.format(new Date(location.getTime()));
        appendLog(datetime + ", ");
    }

    @Override
    public void onProviderDisabled(String provider) {
        AppLog.logString("GPSLoggerService.onProviderDisabled().");
        appendLog("onLocationChanged, ");
    }

    @Override
    public void onProviderEnabled(String provider) {
        AppLog.logString("GPSLoggerService.onProviderEnabled().");
        appendLog("onProviderEnabled, ");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        AppLog.logString("GPSLoggerService.onStatusChanged().");
        appendLog("onStatusChanged, ");
    }

    private void startLoggingService() {

        AppLog.logString("GPSLoggerService.startLoggingService.");
        turnGPSOn();
        db = new DBAdapter(this);
        if (manager == null) {
            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }
        ma = new MainActivity();

        final Criteria criteria = new Criteria();

        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setSpeedRequired(true);
        criteria.setBearingRequired(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        final String bestProvider = manager.getBestProvider(criteria, true);

        if (bestProvider != null && bestProvider.length() > 0) {
            manager.requestLocationUpdates(bestProvider, gpsMinTime, gpsMinDistance, this);
            startTimer();
        } else {
            final List<String> providers = manager.getProviders(true);

            for (final String provider : providers) {
                manager.requestLocationUpdates(provider, gpsMinTime, gpsMinDistance, this);
                startTimer();
            }
        }
    }

    private void stopLoggingService() {
        this.unregisterReceiver(this.mBatInfoReceiver);
        stopSelf();
    }

    private void startMonitoringTimer() {
        monitoringTimer = new Timer();
        AppLog.logString("GPSLoggerService.monitoringTimer.");
        monitoringTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (longitude != 0.0 && latitude != 0.0) {
                    monitoringTimer.cancel();
                    monitoringTimer = null;
                    turnGPSOn();
                    saveData();
                    manager.removeUpdates(GPSLoggerService.this);
                    stopLoggingService();
                }
            }
        }, GPSLoggerService.TIMER_DELAY, GPSLoggerService.TIMER_DELAY);
    }

    private void startTimer() {
        AppLog.logString("GPSLoggerService.countDownTimer.");
        appendLog("startTimer, ");
        // Toast.makeText(getApplicationContext(),"data_mode="+data_mode,
        // Toast.LENGTH_LONG).show();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(15000L, 1000L) {// 15 seconds
                                                            // max
            @Override
            public void onTick(long millisUntilFinished) {
                if (didFindLocation) {
                    countDownTimer.cancel();
                }
            }

            @Override
            public void onFinish() {
                if (!didFindLocation) {
                    appendLog("onFinish, ");
                    manager.removeUpdates(GPSLoggerService.this);
                    // stopSelf()
                    if (data_mode == 1) {
                        cellID();
                    } else {
                        /*
                         * TelephonyManager telephonyManager =
                         * (TelephonyManager
                         * )getSystemService(Context.TELEPHONY_SERVICE);
                         * imeiCellID = telephonyManager.getDeviceId();
                         * SimpleDateFormat sdfDateTime = new
                         * SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
                         * datetimeCellID = sdfDateTime.format(new Date());
                         * db.open();
                         * id=db.insertData(imeiCellID,"null","null"
                         * ,datetimeCellID,"null","null",level1);
                         * db.close();
                         */
                        Toast.makeText(getApplicationContext(), "GPS : Cant find Location", Toast.LENGTH_LONG).show();
                    }
                    stopLoggingService();

                }
            }
        };
        countDownTimer.start();
    }

    private void turnGPSOn() {
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("1"));
            sendBroadcast(poke);
        }
    }

    public void appendLog(String text) {
        // Toast.makeText(getApplicationContext(),"oncreate",
        // Toast.LENGTH_LONG).show();
        File folder3 = new File(Environment.getExternalStorageDirectory(), "BPCLTracker");
        if (!folder3.exists()) {
            folder3.mkdirs();
        }

        try {
            File kmlFile3 = new File(folder3.getPath(), "logfile.txt");
            if (!kmlFile3.exists()) {
                kmlFile3.createNewFile();
            }
            RandomAccessFile fileAccess3 = new RandomAccessFile(kmlFile3, "rw");
            FileLock lock = fileAccess3.getChannel().lock();
            fileAccess3.seek(kmlFile3.length());
            fileAccess3.write(text.getBytes());
            lock.release();
            fileAccess3.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public boolean isInternetOn() {
        ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // ARE WE CONNECTED TO THE NET
        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING
                || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
            return true;
        } else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
            return false;
        }
        return false;
    }

    public int setFlag() {
        final SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean firstRecord = settings.getBoolean("firstRecord", false);
        boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);

        if (firstRecord == true) {
            flag = 0;
            // Toast.makeText(getBaseContext(),"1st record after installation : "+flag,Toast.LENGTH_LONG
            // ).show();
            settings.edit().putBoolean("firstRecord", false).commit();
        } else if (firstRecordAfterBoot == true) {
            flag = 1;
            // Toast.makeText(getBaseContext(),"1st record after boot : "+flag,Toast.LENGTH_LONG
            // ).show();
            settings.edit().putBoolean("justBooted", false).commit();
        } else {
            flag = 2;
            // Toast.makeText(getBaseContext(),"regular : "+flag,Toast.LENGTH_LONG
            // ).show();
        }
        return flag;

    }

    public void cellID() {
        appendLog("in cellID, ");
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
        int cid = cellLocation.getCid();
        int lac = cellLocation.getLac();
        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datetimeCellID = sdfDateTime.format(new Date());
        appendLog(datetimeCellID);
        String cell_Id = String.valueOf(cid);
        String gsm_Loc_Area_Code = String.valueOf(lac);
        // Toast.makeText(getBaseContext(),"cellid="+cell_Id+"\nGsm Location Area Code:"+gsm_Loc_Area_Code,Toast.LENGTH_LONG
        // ).show();

        if (RqsLocation(cid, lac)) {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeiCellID = tm.getDeviceId();
            latitude_cellID = String.valueOf((float) myLatitude / 1000000);
            longitude_cellID = String.valueOf((float) myLongitude / 1000000);
            // Toast.makeText(getBaseContext(),"Lat:"+latitude_cellID+"Long:"+longitude_cellID,Toast.LENGTH_LONG
            // ).show();

            // DBAdapter db=new DBAdapter(this);

            // --add contact----
            db.open();
            setFlag();
            datatype = String.valueOf(flag);
            id = db.insertData(imeiCellID, latitude_cellID, longitude_cellID, datetimeCellID, "null", "null", level1, datatype, "0");
            db.close();

            // --get all contacts----------
            db.open();
            Cursor c = db.getAllData();
            if (c.moveToFirst()) {
                do {
                    DisplayData(c);
                } while (c.moveToNext());
            }
            db.close();

        }// if
        else {
            Toast.makeText(getBaseContext(), "CellID : Can't find Location", Toast.LENGTH_LONG).show();
        }// else
    }// cellID

    private Boolean RqsLocation(int cid, int lac) {
        appendLog("in req location, ");
        // Toast.makeText(getBaseContext(),"inReqloc",Toast.LENGTH_LONG
        // ).show();
        Boolean result = false;
        String urlmmap = "http://www.google.com/glm/mmap";

        try {
            URL url = new URL(urlmmap);
            URLConnection conn = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.connect();
            OutputStream outputStream = httpConn.getOutputStream();
            WriteData(outputStream, cid, lac);
            InputStream inputStream = httpConn.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            dataInputStream.readShort();
            dataInputStream.readByte();
            int code = dataInputStream.readInt();
            if (code == 0) {
                myLatitude = dataInputStream.readInt();
                myLongitude = dataInputStream.readInt();
                result = true;

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;

    }

    private void WriteData(OutputStream out, int cid, int lac) throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(out);
        dataOutputStream.writeShort(21);
        dataOutputStream.writeLong(0);
        dataOutputStream.writeUTF("en");
        dataOutputStream.writeUTF("Android");
        dataOutputStream.writeUTF("1.0");
        dataOutputStream.writeUTF("Web");
        dataOutputStream.writeByte(27);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(3);
        dataOutputStream.writeUTF("");
        dataOutputStream.writeInt(cid);
        dataOutputStream.writeInt(lac);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.flush();
    }

    public void saveData() {

        // Toast.makeText(getApplicationContext(),"in saveData",
        // Toast.LENGTH_LONG).show();
        if (isInternetOn()) {
            appendLog("in saveDataAfter if internet is on, ");
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeino = tm.getDeviceId();

            // DBAdapter db=new DBAdapter(this);

            // --add contact----
            db.open();
            setFlag();
            datatype = String.valueOf(flag);
            id = db.insertData(imeino, gpslatitude, gpslongitude, datetime, gpsaltitude, speed, level1, datatype, "1");
            db.close();
        } else if (!isInternetOn()) {
            appendLog("in saveDataAfter if internet is not not on, ");
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeino = tm.getDeviceId();
            // DBAdapter db=new DBAdapter(this);

            // --add contact----
            db.open();
            setFlag();
            datatype = String.valueOf(flag);
            id = db.insertData(imeino, gpslatitude, gpslongitude, datetime, gpsaltitude, speed, level1, datatype, "1");

            db.close();
        }// elseif
    }// end of saveData() function

    public void sendData() throws ClientProtocolException, IOException {
        // Toast.makeText(getApplicationContext(),"in sendData",
        // Toast.LENGTH_LONG).show();
        appendLog("sendData, ");
        if (isInternetOn()) {

            JSONObject jObject = new JSONObject();
            try {
                // DBAdapter db=new DBAdapter(this);
                db.open();
                Cursor cursor = db.getAllData();
                if (cursor.moveToFirst()) {
                    do {
                        jObject = new JSONObject();
                        jObject.put("Imei", cursor.getString(1));
                        jObject.put("Lat", cursor.getString(2));
                        jObject.put("Long", cursor.getString(3));
                        jObject.put("Gpsdatetime", cursor.getString(4));
                        jObject.put("Altitude", cursor.getString(5));
                        jObject.put("Speed", cursor.getString(6));
                        jObject.put("Battery", cursor.getString(7));
                        jObject.put("DataType", cursor.getString(8));
                        jObject.put("DataSource", cursor.getString(9));

                        String datatoServer = jObject.toString() + "\n";

                        // Toast.makeText(getApplicationContext(),datatoServer,
                        // Toast.LENGTH_LONG).show();

                        HttpEntity entity;
                        HttpClient client = new DefaultHttpClient();
                        String url = "http://some IP/insertv2.php";

                        HttpPost request = new HttpPost(url);
                        StringEntity se = new StringEntity(datatoServer);
                        se.setContentEncoding("UTF-8");
                        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        entity = se;
                        request.setEntity(entity);
                        HttpResponse response = client.execute(request);
                        entity = response.getEntity();
                        db.deleteContacts(cursor.getLong(0));
                    } while (cursor.moveToNext());
                }// if
                db.close();
            }// try
            catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } // method
}// end of service class
11-12 16:43:46.174: E/AndroidRuntime(23962): FATAL EXCEPTION: main
11-12 16:43:46.174: E/AndroidRuntime(23962): android.os.NetworkOnMainThreadException
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at bpcl.gps.tracker.GPSLoggerService.RqsLocation(GPSLoggerService.java:468)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at bpcl.gps.tracker.GPSLoggerService.cellID(GPSLoggerService.java:414)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at bpcl.gps.tracker.GPSLoggerService$3.onFinish(GPSLoggerService.java:288)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.Looper.loop(Looper.java:137)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.app.ActivityThread.main(ActivityThread.java:4947)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.lang.reflect.Method.invokeNative(Native Method)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.lang.reflect.Method.invoke(Method.java:511)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at dalvik.system.NativeStart.main(Native Method)

gpsLogger服务类别:

<uses-sdk android:minSdkVersion="7" 
    android:targetSdkVersion="18"/>
public class GPSLoggerService extends Service implements LocationListener {
    @Override
    public void onCreate() {
        AppLog.logString("GPSLoggerService.onCreate().");
        final SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        AppLog.logString("GPSLoggerService.onCreate().");
        data_mode = settings.getInt("data_mode", 1);
        boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);

        settings.edit().putBoolean("justBooted", false);

        super.onCreate();
        // db = new DBAdapter(this);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        appendLog("in onStartCommend, ");
        AppLog.logString("GPSLoggerService.onStartCommand().");
        this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        startLoggingService();
        startMonitoringTimer();
        try {
            sendData();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // dbadapter = new DBAdapter(this);

        return Service.START_STICKY;
    }

    @Override
    public void onLocationChanged(Location location) {
        appendLog("onLocationChanged, ");
        AppLog.logString("GPSLoggerService.onLocationChanged().");
        didFindLocation = true;
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        altitude = location.getAltitude();
        // Toast.makeText(getApplicationContext(),"lat :"+latitude+"longi :"+longitude,
        // Toast.LENGTH_LONG).show();
        gpsaltitude = String.valueOf(altitude);
        gpslatitude = String.valueOf(latitude);
        gpslongitude = String.valueOf(longitude);
        mps = location.getSpeed();
        kmh = (float) (mps * 3.6);
        speed = Float.toString(kmh);

        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datetime = sdfDateTime.format(new Date(location.getTime()));
        appendLog(datetime + ", ");
    }

    @Override
    public void onProviderDisabled(String provider) {
        AppLog.logString("GPSLoggerService.onProviderDisabled().");
        appendLog("onLocationChanged, ");
    }

    @Override
    public void onProviderEnabled(String provider) {
        AppLog.logString("GPSLoggerService.onProviderEnabled().");
        appendLog("onProviderEnabled, ");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        AppLog.logString("GPSLoggerService.onStatusChanged().");
        appendLog("onStatusChanged, ");
    }

    private void startLoggingService() {

        AppLog.logString("GPSLoggerService.startLoggingService.");
        turnGPSOn();
        db = new DBAdapter(this);
        if (manager == null) {
            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }
        ma = new MainActivity();

        final Criteria criteria = new Criteria();

        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setSpeedRequired(true);
        criteria.setBearingRequired(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        final String bestProvider = manager.getBestProvider(criteria, true);

        if (bestProvider != null && bestProvider.length() > 0) {
            manager.requestLocationUpdates(bestProvider, gpsMinTime, gpsMinDistance, this);
            startTimer();
        } else {
            final List<String> providers = manager.getProviders(true);

            for (final String provider : providers) {
                manager.requestLocationUpdates(provider, gpsMinTime, gpsMinDistance, this);
                startTimer();
            }
        }
    }

    private void stopLoggingService() {
        this.unregisterReceiver(this.mBatInfoReceiver);
        stopSelf();
    }

    private void startMonitoringTimer() {
        monitoringTimer = new Timer();
        AppLog.logString("GPSLoggerService.monitoringTimer.");
        monitoringTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (longitude != 0.0 && latitude != 0.0) {
                    monitoringTimer.cancel();
                    monitoringTimer = null;
                    turnGPSOn();
                    saveData();
                    manager.removeUpdates(GPSLoggerService.this);
                    stopLoggingService();
                }
            }
        }, GPSLoggerService.TIMER_DELAY, GPSLoggerService.TIMER_DELAY);
    }

    private void startTimer() {
        AppLog.logString("GPSLoggerService.countDownTimer.");
        appendLog("startTimer, ");
        // Toast.makeText(getApplicationContext(),"data_mode="+data_mode,
        // Toast.LENGTH_LONG).show();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(15000L, 1000L) {// 15 seconds
                                                            // max
            @Override
            public void onTick(long millisUntilFinished) {
                if (didFindLocation) {
                    countDownTimer.cancel();
                }
            }

            @Override
            public void onFinish() {
                if (!didFindLocation) {
                    appendLog("onFinish, ");
                    manager.removeUpdates(GPSLoggerService.this);
                    // stopSelf()
                    if (data_mode == 1) {
                        cellID();
                    } else {
                        /*
                         * TelephonyManager telephonyManager =
                         * (TelephonyManager
                         * )getSystemService(Context.TELEPHONY_SERVICE);
                         * imeiCellID = telephonyManager.getDeviceId();
                         * SimpleDateFormat sdfDateTime = new
                         * SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
                         * datetimeCellID = sdfDateTime.format(new Date());
                         * db.open();
                         * id=db.insertData(imeiCellID,"null","null"
                         * ,datetimeCellID,"null","null",level1);
                         * db.close();
                         */
                        Toast.makeText(getApplicationContext(), "GPS : Cant find Location", Toast.LENGTH_LONG).show();
                    }
                    stopLoggingService();

                }
            }
        };
        countDownTimer.start();
    }

    private void turnGPSOn() {
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("1"));
            sendBroadcast(poke);
        }
    }

    public void appendLog(String text) {
        // Toast.makeText(getApplicationContext(),"oncreate",
        // Toast.LENGTH_LONG).show();
        File folder3 = new File(Environment.getExternalStorageDirectory(), "BPCLTracker");
        if (!folder3.exists()) {
            folder3.mkdirs();
        }

        try {
            File kmlFile3 = new File(folder3.getPath(), "logfile.txt");
            if (!kmlFile3.exists()) {
                kmlFile3.createNewFile();
            }
            RandomAccessFile fileAccess3 = new RandomAccessFile(kmlFile3, "rw");
            FileLock lock = fileAccess3.getChannel().lock();
            fileAccess3.seek(kmlFile3.length());
            fileAccess3.write(text.getBytes());
            lock.release();
            fileAccess3.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public boolean isInternetOn() {
        ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // ARE WE CONNECTED TO THE NET
        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING
                || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
            return true;
        } else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
            return false;
        }
        return false;
    }

    public int setFlag() {
        final SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean firstRecord = settings.getBoolean("firstRecord", false);
        boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);

        if (firstRecord == true) {
            flag = 0;
            // Toast.makeText(getBaseContext(),"1st record after installation : "+flag,Toast.LENGTH_LONG
            // ).show();
            settings.edit().putBoolean("firstRecord", false).commit();
        } else if (firstRecordAfterBoot == true) {
            flag = 1;
            // Toast.makeText(getBaseContext(),"1st record after boot : "+flag,Toast.LENGTH_LONG
            // ).show();
            settings.edit().putBoolean("justBooted", false).commit();
        } else {
            flag = 2;
            // Toast.makeText(getBaseContext(),"regular : "+flag,Toast.LENGTH_LONG
            // ).show();
        }
        return flag;

    }

    public void cellID() {
        appendLog("in cellID, ");
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
        int cid = cellLocation.getCid();
        int lac = cellLocation.getLac();
        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datetimeCellID = sdfDateTime.format(new Date());
        appendLog(datetimeCellID);
        String cell_Id = String.valueOf(cid);
        String gsm_Loc_Area_Code = String.valueOf(lac);
        // Toast.makeText(getBaseContext(),"cellid="+cell_Id+"\nGsm Location Area Code:"+gsm_Loc_Area_Code,Toast.LENGTH_LONG
        // ).show();

        if (RqsLocation(cid, lac)) {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeiCellID = tm.getDeviceId();
            latitude_cellID = String.valueOf((float) myLatitude / 1000000);
            longitude_cellID = String.valueOf((float) myLongitude / 1000000);
            // Toast.makeText(getBaseContext(),"Lat:"+latitude_cellID+"Long:"+longitude_cellID,Toast.LENGTH_LONG
            // ).show();

            // DBAdapter db=new DBAdapter(this);

            // --add contact----
            db.open();
            setFlag();
            datatype = String.valueOf(flag);
            id = db.insertData(imeiCellID, latitude_cellID, longitude_cellID, datetimeCellID, "null", "null", level1, datatype, "0");
            db.close();

            // --get all contacts----------
            db.open();
            Cursor c = db.getAllData();
            if (c.moveToFirst()) {
                do {
                    DisplayData(c);
                } while (c.moveToNext());
            }
            db.close();

        }// if
        else {
            Toast.makeText(getBaseContext(), "CellID : Can't find Location", Toast.LENGTH_LONG).show();
        }// else
    }// cellID

    private Boolean RqsLocation(int cid, int lac) {
        appendLog("in req location, ");
        // Toast.makeText(getBaseContext(),"inReqloc",Toast.LENGTH_LONG
        // ).show();
        Boolean result = false;
        String urlmmap = "http://www.google.com/glm/mmap";

        try {
            URL url = new URL(urlmmap);
            URLConnection conn = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.connect();
            OutputStream outputStream = httpConn.getOutputStream();
            WriteData(outputStream, cid, lac);
            InputStream inputStream = httpConn.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            dataInputStream.readShort();
            dataInputStream.readByte();
            int code = dataInputStream.readInt();
            if (code == 0) {
                myLatitude = dataInputStream.readInt();
                myLongitude = dataInputStream.readInt();
                result = true;

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;

    }

    private void WriteData(OutputStream out, int cid, int lac) throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(out);
        dataOutputStream.writeShort(21);
        dataOutputStream.writeLong(0);
        dataOutputStream.writeUTF("en");
        dataOutputStream.writeUTF("Android");
        dataOutputStream.writeUTF("1.0");
        dataOutputStream.writeUTF("Web");
        dataOutputStream.writeByte(27);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(3);
        dataOutputStream.writeUTF("");
        dataOutputStream.writeInt(cid);
        dataOutputStream.writeInt(lac);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.flush();
    }

    public void saveData() {

        // Toast.makeText(getApplicationContext(),"in saveData",
        // Toast.LENGTH_LONG).show();
        if (isInternetOn()) {
            appendLog("in saveDataAfter if internet is on, ");
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeino = tm.getDeviceId();

            // DBAdapter db=new DBAdapter(this);

            // --add contact----
            db.open();
            setFlag();
            datatype = String.valueOf(flag);
            id = db.insertData(imeino, gpslatitude, gpslongitude, datetime, gpsaltitude, speed, level1, datatype, "1");
            db.close();
        } else if (!isInternetOn()) {
            appendLog("in saveDataAfter if internet is not not on, ");
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeino = tm.getDeviceId();
            // DBAdapter db=new DBAdapter(this);

            // --add contact----
            db.open();
            setFlag();
            datatype = String.valueOf(flag);
            id = db.insertData(imeino, gpslatitude, gpslongitude, datetime, gpsaltitude, speed, level1, datatype, "1");

            db.close();
        }// elseif
    }// end of saveData() function

    public void sendData() throws ClientProtocolException, IOException {
        // Toast.makeText(getApplicationContext(),"in sendData",
        // Toast.LENGTH_LONG).show();
        appendLog("sendData, ");
        if (isInternetOn()) {

            JSONObject jObject = new JSONObject();
            try {
                // DBAdapter db=new DBAdapter(this);
                db.open();
                Cursor cursor = db.getAllData();
                if (cursor.moveToFirst()) {
                    do {
                        jObject = new JSONObject();
                        jObject.put("Imei", cursor.getString(1));
                        jObject.put("Lat", cursor.getString(2));
                        jObject.put("Long", cursor.getString(3));
                        jObject.put("Gpsdatetime", cursor.getString(4));
                        jObject.put("Altitude", cursor.getString(5));
                        jObject.put("Speed", cursor.getString(6));
                        jObject.put("Battery", cursor.getString(7));
                        jObject.put("DataType", cursor.getString(8));
                        jObject.put("DataSource", cursor.getString(9));

                        String datatoServer = jObject.toString() + "\n";

                        // Toast.makeText(getApplicationContext(),datatoServer,
                        // Toast.LENGTH_LONG).show();

                        HttpEntity entity;
                        HttpClient client = new DefaultHttpClient();
                        String url = "http://some IP/insertv2.php";

                        HttpPost request = new HttpPost(url);
                        StringEntity se = new StringEntity(datatoServer);
                        se.setContentEncoding("UTF-8");
                        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        entity = se;
                        request.setEntity(entity);
                        HttpResponse response = client.execute(request);
                        entity = response.getEntity();
                        db.deleteContacts(cursor.getLong(0));
                    } while (cursor.moveToNext());
                }// if
                db.close();
            }// try
            catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } // method
}// end of service class
11-12 16:43:46.174: E/AndroidRuntime(23962): FATAL EXCEPTION: main
11-12 16:43:46.174: E/AndroidRuntime(23962): android.os.NetworkOnMainThreadException
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at bpcl.gps.tracker.GPSLoggerService.RqsLocation(GPSLoggerService.java:468)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at bpcl.gps.tracker.GPSLoggerService.cellID(GPSLoggerService.java:414)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at bpcl.gps.tracker.GPSLoggerService$3.onFinish(GPSLoggerService.java:288)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.os.Looper.loop(Looper.java:137)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at android.app.ActivityThread.main(ActivityThread.java:4947)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.lang.reflect.Method.invokeNative(Native Method)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at java.lang.reflect.Method.invoke(Method.java:511)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
11-12 16:43:46.174: E/AndroidRuntime(23962):    at dalvik.system.NativeStart.main(Native Method)
公共类gpsLogger服务扩展服务实现LocationListener{
@凌驾
public void onCreate(){
日志字符串(“GPSLoggerService.onCreate()”;
最终SharedReferences设置=GetSharedReferences(首选名称,模式\私有);
日志字符串(“GPSLoggerService.onCreate()”;
data_mode=settings.getInt(“data_mode”,1);
boolean firstRecordAfterBoot=settings.getBoolean(“justBooted”,false);
settings.edit().putBoolean(“justBooted”,false);
super.onCreate();
//db=新的DBAdapter(本);
}
公共int onStartCommand(Intent Intent、int标志、int startId){
appendLog(“在OnStartLog中,”);
日志字符串(“GPSLoggerService.onStartCommand()”;
this.registerReceiver(this.mBatInfoReceiver,新的IntentFilter(Intent.ACTION\u BATTERY\u CHANGED));
惊人的服务();
开始监视计时器();
试一试{
sendData();
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
//dbadapter=新的dbadapter(此);
return Service.START\u STICKY;
}
@凌驾
已更改位置上的公共无效(位置){
附录日志(“onLocationChanged”);
日志字符串(“GPSLoggerService.onLocationChanged()”;
didFindLocation=true;
纬度=位置。getLatitude();
longitude=location.getLongitude();
高度=位置。getAltitude();
//Toast.makeText(getApplicationContext(),“纬度:”+纬度+“经度:”+经度,
//Toast.LENGTH_LONG).show();
gpsaltudence=字符串的值(高度);
gpslatitude=String.valueOf(纬度);
gpslongitude=String.valueOf(经度);
mps=location.getSpeed();
kmh=(浮动)(mps*3.6);
速度=浮动扭矩(公里小时);
SimpleDateFormat sdfDateTime=新的SimpleDateFormat(“yyyy-MM-dd HH:MM:ss”);
datetime=sdfDateTime.format(新日期(location.getTime());
附录日志(日期时间+“,”);
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
日志字符串(“GPSLoggerService.onProviderDisabled()”;
附录日志(“onLocationChanged”);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
logString(“gpsLogger服务.onProviderEnabled()”;
附录日志(“onProviderEnabled,”);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
日志字符串(“GPSLoggerService.onStatusChanged()”;
附录日志(“onStatusChanged”);
}
私家侦探服务(){
日志字符串(“GPSLoggerService.startLoggingService”);
turnGPSOn();
db=新的DBAdapter(本);
if(manager==null){
manager=(LocationManager)getSystemService(Context.LOCATION\u服务);
}
ma=新的主活动();
最终标准=新标准();
标准.设定准确度(标准.准确度/精细度);
标准。setAltitudeRequired(真);
标准。设置所需速度(真);
标准。需要设置(正确);
标准。设置功率要求(标准。功率低);
最后一个字符串bestProvider=manager.getBestProvider(条件为true);
if(bestProvider!=null&&bestProvider.length()>0){
manager.requestLocationUpdates(bestProvider、gpsMinTime、gpsMinDistance、this);
startTimer();
}否则{
最终列表提供者=manager.getProviders(true);
for(最终字符串提供程序:提供程序){
requestLocationUpdates(provider、gpsMinTime、gpsMinDistance、this);
startTimer();
}
}
}
私人作废stopLoggingService(){
本.未注册接收人(本.mBatInfoReceiver);
stopSelf();
}
私有void startMonitoringTimer(){
monitoringTimer=新计时器();
logString(“GPSLoggerService.monitoringTimer.”);
monitoringTimer.scheduleAtFixedRate(新TimerTask(){
@凌驾
公开募捐{
如果(经度!=0.0和纬度!=0.0){
monitoringTimer.cancel();
monitoringTimer=null;
turnGPSOn();
saveData();
manager.removeUpdates(gpslogger.this);
stopLoggingService();
}
}
},GPSLoggerService.TIMER\u DELAY,GPSLoggerService.TIMER\u DELAY);
}
私有void startTimer(){
logString(“GPSLoggerService.countDownTimer.”);
appendLog(“startTimer”);
//Toast.makeText(getApplicationContext(),“data\u mode=“+data\u mode,
//Toast.LENGTH_LONG).show();
if(倒计时!=null){
倒计时。取消();
倒计时=空;
}
倒计时=新的倒计时(15000L,1000L){//15秒
//马克斯
@凌驾