应用程序无响应错误

时间:2013-12-31 06:23:27

标签: android android-asynctask networkonmainthread

我有一个跟踪应用,每2分钟根据gps和手机ID进行跟踪。我已经使用AlarmManager的setRepeting()从MainActivity启动了一个服务。然后在该服务中我写了一个asynctask.In onPreExecute()我使用gps或cellid获取纬度和经度。在doInBackground()中,我从sqlite db获取数据并发送到服务器。即使在asynctask应用程序中编写所有网络相关代码后,有时也会说应用程序没有响应。并按下确定它重新启动。我该怎么做才能避免这种情况。

public class SendDataAsync extends Service {
Logger logger ;
Context con;
String level1;

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Toast.makeText(getApplicationContext(),"in onReceive of GPSLoggerService",
        // Toast.LENGTH_LONG).show();
        // TODO Auto-generated method stub
        int level = intent.getIntExtra("level", 0);
        int scale = intent.getIntExtra("scale", 100);
        level1 = String.valueOf(level * 100 / scale);
    }
}; // battery level

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    LogConfigurator logConfigurator = new LogConfigurator();
    logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator + "logs"+ File.separator + "log4j.txt");

    logConfigurator.setRootLevel(Level.INFO);
    logConfigurator.setLevel("org.apache", Level.INFO);
    logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
    logConfigurator.setMaxFileSize(1024 * 1024 * 5);
    logConfigurator.setImmediateFlush(true);
    logConfigurator.configure();
    logger = Logger.getLogger(SendDataAsync.class);
    super.onCreate();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    try
    {
        this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));
    FetchCordinates fetchCordinates = new FetchCordinates();
    fetchCordinates.execute();
    }
    catch (Exception e) {
        // TODO: handle exception
        logger.info(e);
    }
    return super.onStartCommand(intent, flags, startId);
}

FetchCordinates

public class FetchCordinates extends AsyncTask<String, Integer, String> {

    private Timer monitoringTimer = null;
    private static final int TIMER_DELAY = 1000;
    private LocationManager locManager;     

    private static final int gpsMinTime = 1000;
    private static final int gpsMinDistance = 1;
    private double latitude = 0.0;
    private double longitude = 0.0;
    private double altitude = 0.0;
    float mps;
    float kmh;
    SendDataAsync sda;
    Runtime runtime1;
    Process proc1;
    int returnVal1 = 0;
    int data_mode = 0;
    int myLatitude, myLongitude;
    String imeiCellID, datetimeCellID;
    String latitude_cellID, longitude_cellID;
    public String gpslatitude = null;
    public String gpslongitude = null;
    public String gpsaltitude = null;
    private String speed = null;
    private String datetime = null;
    private String imeino = null;
    private String datatype = null;

    private CountDownTimer countDownTimer = null;
    DBAdapter db;
    int flag;
    Context context;
    boolean didFindLocation = false;
    long id;
    public static final String PREFS_NAME = "bp";

    public LocationManager mLocationManager;

    @Override
    protected void onPreExecute() {
        final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
                MODE_PRIVATE);
        data_mode = settings.getInt("data_mode", 1);
        startLoggingService();
        startMonitoringTimer();

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            sendData();
        } catch (ClientProtocolException e) {
            logger.info(e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.info(e.toString());
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {

    }

    protected void removeGps()
 {
     locManager.removeUpdates(locationListener);
 }

 private void startLoggingService() {
        db = new DBAdapter(SendDataAsync.this);
        if (locManager == null) {
            locManager = (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 = locManager.getBestProvider(criteria, true);

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

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

 private void startTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(20000L, 1000L) {// 15 seconds max
            @Override
            public void onTick(long millisUntilFinished) {
                if (didFindLocation) {
                    countDownTimer.cancel();
                }
            }

            @Override
            public void onFinish() {
                if (!didFindLocation) {
                    removeGps();
                      if(data_mode==1)
                      {
                          monitoringTimer.cancel();
                         cellID(); 
                      }
                      else { 
                      Toast.makeText(getApplicationContext
                      (),"GPS : Cant find Location", Toast.LENGTH_LONG).show();
                      }

                    stopLoggingService();

                }//if
            }//inFin
        };
        countDownTimer.start();
    }
 // class  location listener
 private final LocationListener locationListener = new LocationListener()
 {
        @Override
        public void onLocationChanged(Location location) {

            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()));
        }

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

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

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

  public void saveData() {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeino = tm.getDeviceId();

             DBAdapter db=new DBAdapter(SendDataAsync.this);

            setFlag();      
            datatype = String.valueOf(flag);
            // --add contact----

            db.open();

            id = db.insertData(imeino, gpslatitude, gpslongitude, datetime,
                    gpsaltitude, speed, level1, datatype, "1");
            db.close();
    }// end of saveData() function

  private void startMonitoringTimer() {
        monitoringTimer = new Timer();
        monitoringTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {


                if (longitude != 0.0 && latitude != 0.0) {

                    monitoringTimer.cancel();
                    monitoringTimer = null;
                    // turnGPSOn();
                    //didFindLocation=false;
                    saveData();
                    removeGps();                        
                    stopLoggingService();
                }
            }
        },TIMER_DELAY,TIMER_DELAY);
    }

  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() {
        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());
        // Toast.makeText(getBaseContext(),"cellid="+cell_Id+"\nGsm Location Area Code:"+gsm_Loc_Area_Code,Toast.LENGTH_LONG
        // ).show();

        CellidAsync cellasy=new CellidAsync();
        String pass = null;
        try {
            pass = cellasy.execute(cid,lac).get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String[] arr=pass.split(",");

        if (Boolean.valueOf(arr[0])) {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            imeiCellID = tm.getDeviceId();
            myLatitude=Integer.valueOf(arr[1]);
            myLongitude=Integer.valueOf(arr[2]);
            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



    public void sendData() throws ClientProtocolException, IOException
    {
        //Toast.makeText(getApplicationContext(),"in sendData", Toast.LENGTH_LONG).show();
        enableInternet();
        setAirplaneMode();
        runtime1 = Runtime.getRuntime();
        proc1 = runtime1.exec("ping -c 1 some ip");

        try {
            returnVal1 = proc1.waitFor();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        boolean reachable1 = (returnVal1==0);
        if(reachable1==true)
        {

        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 dt=cursor.getString(4).replace(" ","*");


                        String datatoServer=cursor.getString(1)+","+cursor.getString(2)+","+cursor.getString(3)+","+dt+","+cursor.getString(5)+","+cursor.getString(6)+","+cursor.getString(7)+","+cursor.getString(8)+","+cursor.getString(9);
                        //Toast.makeText(getApplicationContext(),datatoServer, Toast.LENGTH_LONG).show();

                            HttpEntity entity1;
                            HttpClient client1 = new DefaultHttpClient();
                            String url1 ="http:/url="+datatoServer;
                            HttpPost request1 = new HttpPost(url1);
                            StringEntity se1 = new StringEntity(datatoServer);
                            se1.setContentEncoding("UTF-8");
                            se1.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                            "application/json"));
                            entity1 = se1;
                            //request1.setEntity(entity1);
                            HttpResponse response1 = client1.execute(request1);
                            entity1 = response1.getEntity();

                        //----------------------------------------------------------------

                        db.deleteContacts(cursor.getLong(0));
                    }while(cursor.moveToNext());
                }//if
                db.close();                     
            }//try
            catch (JSONException e) 
            {
                e.printStackTrace();
                logger.info(""+e);
            }
            catch(Exception e)
            {
                logger.info(""+e);
            }
        }//if
        }//if ping
    }  //method 

    public void setAirplaneMode()
    {
        // Check for Airplane Mode
        boolean isEnabled = Settings.System.getInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0) == 1;

       if (isEnabled) {
            // toggle airplane mode
            Settings.System.putInt(getContentResolver(),
            Settings.System.AIRPLANE_MODE_ON,isEnabled ? 0 : 1);
            // Post an intent to reload
            Intent intent = new Intent(                 

Intent.ACTION_AIRPLANE_MODE_CHANGED);
            intent.putExtra("state", !isEnabled);
            sendBroadcast(intent);
       }
    }

    public void enableInternet()
    {       
        try{
            TelephonyManager telephonyManager = (TelephonyManager)
            getSystemService(Context.TELEPHONY_SERVICE);

            boolean isEnabled;
            if(telephonyManager.getDataState() == 

TelephonyManager.DATA_CONNECTED){
                //Toast.makeText(GPSLoggerService.this, "true", Toast.LENGTH_LONG).show();
                isEnabled = true;
            }else{
                //Toast.makeText(GPSLoggerService.this, "false", Toast.LENGTH_LONG).show();
                isEnabled = false;  
            }   
    if (isEnabled) {
    } else {
        ConnectivityManager dataManager;
        dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Method dataMtd = ConnectivityManager.class.getDeclaredMethod

("setMobileDataEnabled", boolean.class);dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);    
    }
        }
        catch(Exception e){
            logger.info(""+e);
        }
}//enable internet


}//async
private void stopLoggingService() {
    this.unregisterReceiver(this.mBatInfoReceiver);
    stopSelf();
}
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

}

1 个答案:

答案 0 :(得分:0)

你应该在doInBackground()方法中获取lat和long,而不是在preExecute()中获取。

获取位置可能需要一些时间,应该在后台完成。这就是你遇到这个问题的原因。