在android中随时发送GPS坐标

时间:2013-01-22 21:13:08

标签: android gps locationmanager

有下一个问题,需要一个程序将坐标随时发送到我的服务器。我创建了一个任务管理器,可以发送坐标,只购买前三到五次工作并死亡。

这是我的代码,请问我的问题是什么?

我的主要活动:

public class MainActivity extends Activity {
public int ingreso =0;      
double latitud=0;
double longitud=0;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public double lat1=0;
public double lon1=0;enter code here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final InstallationId Miid = new InstallationId();


    Alarmas mUIUpdater = new Alarmas(new Runnable() {
         @Override 
         public void run() {
            // do stuff ...
             /* Use the LocationManager class to obtain GPS locations */

            LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

            LocationListener mlocListener = new MyLocationListener();

            isGPSEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled )
            {
                /*NO HAY GPS*/
                Toast.makeText( getApplicationContext(),"El GPS se encuentra desactivado. Favor activarlo para determinar el Centro de embellecimiento mas cercano",Toast.LENGTH_LONG ).show();
                Intent intentRedirectionGPSSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                intentRedirectionGPSSettings.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivityForResult(intentRedirectionGPSSettings, 0);
            }
            else
            {           
                if (isGPSEnabled)
                {
                    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

                }
                else
                {
                    if (isNetworkEnabled)
                    {
                        mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);

                    }
                }
            }



            lat1=((MyLocationListener) mlocListener).GetLatitud();
            Log.d("Enviando datos", "es " + ((MyLocationListener) mlocListener).GetLatitud());
            lon1=((MyLocationListener) mlocListener).GetLongitud();
            String miurl="http://casoft.com.co/evvc/registro.php?idphone=" + Miid.id(getApplicationContext()) + "&lat1=" + lat1 + "&lon1=" + lon1;              
            new Tareas().execute(miurl);                
            mlocManager.removeUpdates(mlocListener);


         }
    });

    mUIUpdater.startUpdates();



    //new Tareas().execute("http://casoft.com.co/evvc/registro.php?idphone=1&lat1=1&lon1=2");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}


public class MyLocationListener implements LocationListener

{





    @Override
    public void onLocationChanged(Location loc)

    {
        loc.getLatitude();
        loc.getLongitude(); 
            latitud = loc.getLatitude();
            longitud= loc.getLongitude();
            Log.d("Enviando datos", latitud + "es " + longitud);

    }


    @Override

    public void onProviderDisabled(String provider)

    {


        ingreso=0;
    }


    @Override

    public void onProviderEnabled(String provider)

    {

        Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();

    }


    @Override

    public void onStatusChanged(String provider, int status, Bundle extras)

    {


    }

    public double GetLatitud()
    {

        return latitud;

    }

    public double GetLongitud()
    {

        return longitud;
    }

}/* End of Class MyLocationListener */


public void Sael(View view) {
    Intent i = new Intent(this, navegador.class );
    startActivity(i);
}

}

这是为了获得idphone:

public class InstallationId {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";

public synchronized static String id(Context context) {
    if (sID == null) {  
        File installation = new File(context.getFilesDir(), INSTALLATION);
        try {
            if (!installation.exists())
                writeInstallationFile(installation);
            sID = readInstallationFile(installation);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return sID;
}

private static String readInstallationFile(File installation) throws IOException {
    RandomAccessFile f = new RandomAccessFile(installation, "r");
    byte[] bytes = new byte[(int) f.length()];
    f.readFully(bytes);
    f.close();
    return new String(bytes);
}

private static void writeInstallationFile(File installation) throws IOException {
    FileOutputStream out = new FileOutputStream(installation);
    String id = UUID.randomUUID().toString();
    out.write(id.getBytes());
    out.close();
}

}

这就是警报:

public class Alarmas {
    private Handler mHandler = new Handler(); // TODO Don't know if this is created in the UI thread
    private Runnable mStatusChecker;
    private int UPDATE_INTERVAL = 9000;

    /**
     * Creates an UIUpdater object, that can be used to
     * perform UIUpdates on a specified time interval.
     * 
     * @param uiUpdater A runnable containing the update routine.
     */
    public Alarmas(final Runnable uiUpdater){
        mStatusChecker = new Runnable() {
            @Override
            public void run() {
                // Run the passed runnable
                uiUpdater.run();

                // Re-run it after the update interval
                mHandler.postDelayed(this, UPDATE_INTERVAL);
            }
        };
    }



    /**
     * The same as the default constructor, but specifying the
     * intended update interval.
     * 
     * @param uiUpdater A runnable containing the update routine.
     * @param interval  The interval over which the routine
     *                  should run (milliseconds).
     */
    public Alarmas(Runnable uiUpdater, int interval){
        this(uiUpdater);
        UPDATE_INTERVAL = interval;
    }

    /**
     * Starts the periodical update routine (mStatusChecker 
     * adds the callback to the handler).
     */
    public void startUpdates(){
        mStatusChecker.run();
    }

    /**
     * Stops the periodical update routine from running,
     * by removing the callback.
     */
    public void stopUpdates(){
        mHandler.removeCallbacks(mStatusChecker);
    }

}

这就是TASK

class Tareas extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    Log.d("Enviando datos", "Solicitando");

    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Do anything with response..
}

}

感谢您的帮助。

Pda:我需要这个程序一直工作,只在任何时间向我发送GPS报告,因为测试在任何9秒内都有UPDATE_INTERVAL。

1 个答案:

答案 0 :(得分:0)

  

仅购买前三到五次工作并死亡。

这可能是因为Android很可能终止了您的流程。

请使用AlarmManager进行每小时一次的工作。每小时获取一次位置修复有点棘手 - 我有a LocationPoller library可以帮助解决这个问题。