0

我的是一个安卓追踪应用。它获取 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"/>

GPSLoggerService 类:

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)
4

1 回答 1

-2

尝试在 onCreate 方法中使用此代码。

int SDK_INT = android.os.Build.VERSION.SDK_INT;

if (SDK_INT>8){

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

}

并将 Android Manifest 设置为类似这样

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" android:maxSdkVersion="16"/>
于 2013-11-12T11:30:56.153 回答