1

次の問題があります。サーバーにいつでも座標を送信するプログラムが必要です。私はタスクマネージャーを作成し、座標を送信することができます。

これは私のコードです。私の問題はどうですか?

私のメインアクティビティ:

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 レポートを送信してください。テストでは、UPDATE_INTERVAL が 9 秒あります。

4

1 に答える 1

0

購入のみ 最初の 3 ~ 5 回の作業で死亡しました。

これはおそらく、Android がプロセスを終了したためです。

AlarmManager1時間に1回の業務に是非ご利用ください。1 時間に 1 回位置情報を取得するのは少し難しいです。これを支援するLocationPollerライブラリがあります。

于 2013-01-22T21:19:08.897 に答える