开发者

Android: save gps location with every other data send and sent to webserver

In my mainActivity I have a listview where the user can select one. As a sample, there are 3 list in the mainActivity which is startTripActivity, ClockinActivity, CustomerSvcActivity.

For starttripactivity, the user would click that and it would show the button and once clicked it would show toast message info of their location and send to the server. For clockinActivity, user can click to display the current time/date and click the button to send that data to the server.

For customersvcActivity, user would click the button and it will open the barcode scanner and return the result and send that to the server. What I want to do is each of those activity that was sent to the server I also want to send the gps location with the data. Example, starttrip would send the gps info to the server, clockin would send the clockin time/date plus their gps location info where they clocked in, and barcode result data plus their gps location info where they scanned the code sent to the server.

I would like to see some samples and suggestions. All the searches I've found are mostly how to get the gps data every xx minutes which isnt exactly what im looking for and few others doesn't really help me much. The very bottom of this post are the codes of my sample communicating with the webserver.

Thanks

MainActivity.java

public class Customer extends ListActivity
{   
    CustomerListItem[] items = { 
            new CustomerListItem("Start Trip", StartTripActivity.class), 
            new CustomerListItem("Clock in", ClockinActivity.class), 
            new CustomerListItem("Customer Svc", CustomerSvcActivity.class), 

    private String username;


    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.customer);
        setListAdapter(new ArrayAdapter<CustomerListItem>(
                this, android.R.layout.simple_list_item_1, items));
        selection = (TextView) findViewById(R.id.selection);
        resultsTxt = (TextView) findViewById(R.id.cancel);


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);
        final Intent intent = new Intent(this, items[position].getActivity());
        startActivityForResult(intent, position);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK)
        {
            // Perform different actions based on from which activity is
            // the application returning:
            switch (requestCode)
            {
                case 0:
                    // TODO: handle the return of the StartTripActivity
                    break;
.............
}

StartTripActivity

public class StartTripActivity extends Activity {

    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

    protected LocationManager locationManager;

    protected Button retrieveLocationButton;


    private void Pop(String string) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);

        retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

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

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );

    retrieveLocationButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showCurrentLocation();

}
    protected void showCurrentLocation() {

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(StartTripActivity.this, message,
                    Toast.LENGTH_LONG).show();

        }
        Intent i = new Intent(getApplicationContext(), Customer.class);
        startActivity(i);

    }   

    class MyLocationListener implements LocationListener {

        @SuppressWarnings("null")
        public void onLocationChanged(Location location) {
            String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(StartTripActivity.this, message, Toast.LENGTH_LONG).show();

            } catch (Exception e) {

            }
        }

        public void onStatusChanged(String s, int i, Bundle b) {
            Toast.makeText(StartTripActivity.this, "Provider status changed",
                    Toast.LENGTH_SHORT).show();
        }

        public void onProviderDisabled(String s) {
            Toast.makeText(StartTripActivity.this,
                    "Provider disabled by the user. GPS turned off",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String s) {
            Toast.makeText(StartTripActivity.this,
                    "Provider enabled by the user. GPS turned on",
                    Toast.LENGTH_LONG).show();
        }

ClockinActivity.java

public class ClockinActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.clockin);

        TextView textView= (TextView)findViewById(R.id.Date);
        String currentDateTimeString = DateFormat.getDateInstance().format(new Date());

     textView.setText(currentDateTimeString);

        Thread myThread = null;

        Runnable runnable = new CountDownRunner();
       myThread= new Thread(runnable);   
        myThread.start();

   }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Pop("Back Button");
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

   private void Pop(String string) {
        // TODO Auto-generated method stub

    }
public void doWork() {

   runOnUiThread(new Runnable() {
       public void run() {
           try{
       TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
                   Date dt = new Date();
                   int hours = dt.getHours();
                   int minutes = dt.getMinutes();
                   int seconds = dt.getSeconds();
                   String curTime = hours + ":"+ minutes + ":"+ seconds;
                   txtCurrentTime.setText(curTime);
       }catch (Exception e) {

       }
       }
   });

   }

   class CountDownRunner implements Runnable{
       // @Override
       public void run() {
               while(!Thread.currentThread().isInterrupted()){
开发者_Go百科                   try {
                   doWork();
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                           Thread.currentThread().interrupt();
                   }catch(Exception e){
                   }
               }   

Button btn = (Button) findViewById(R.id.btn_OK);

btn.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View view) {        

        Intent i = new Intent(getApplicationContext(), Customer.class);
        startActivity(i);

        //finish(); 
    }

CustomerSvcActivity.java
public class CustomerSvcActivity extends Activity {
    private Button btnscan;

    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {  
        if(keyCode==KeyEvent.KEYCODE_BACK)  
        {  
            this.startActivity(new Intent(CustomerSvcActivity.this,Customer.class));  
        }  
        return true;  
    }  


    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customersvc);

        btnscan = (Button) findViewById(R.id.scanbtn);


        btnscan.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                IntentIntegrator.initiateScan(CustomerSvcActivity.this); 
    }
        });
            }
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
                switch(requestCode) {
                    case IntentIntegrator.REQUEST_CODE: {
                        if (resultCode != RESULT_CANCELED) {
                            IntentResult scanResult =
            IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                            if (scanResult != null) {
                                String upc = scanResult.getContents();
                                // need to return the result without display and send to server???

                            }
                                                }
                        break;

Sample class of sending data

public class Sample extends Activity {
    /** Called when the activity is first created. */
    TextView result;
    EditText text;
    Button send;
    private ArrayList<NameValuePair> postParameters;
    AlertDialog.Builder alert;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        alert = new AlertDialog.Builder(this);
        alert.setCancelable(true);

        result=(TextView)findViewById(R.id.result);
        text=(EditText)findViewById(R.id.text);
        send=(Button)findViewById(R.id.send);

        send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                //postParameters.add(new BasicNameValuePair("text",
                        //text.getText().toString()));
                postData(text.getText().toString());
                //saveData();
                showData();
            }
public void showData()
    {
        try {
            String response = CustomHttpClient
                    .executeHttpGet("http://www.merrill.com/android.php");

            result.setText(response);
        } catch (Exception e) {
        }
    }


Android's Location API is periodic only. If you want a one-off location fix triggered by any of the user's actions, you can use LocationManager.getLastKnownLocation(), but you'll want to check the returned fix's time stamp. To get a new fix what you really need to do is:

-request location data using a small period time 
-wait until the first location fix comes in 
-cancel your location request

This will require asynchronous communication, which you can do however you're most comfortable with. You can use callback functions or pass in a runnable or a message passing system if you have access to one that's easy to include. The GPS might take a couple minutes to return, and it might not be able to get a valid fix so you'll have to account for that.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜