如何使用广播接收器检查gps跟踪半小时?

时间:2012-01-09 09:02:14

标签: android gps broadcastreceiver

Hai我试图使用BroadCast Receiver.its正常工作获得gps位置,但我希望每隔半小时获取一次该位置。我使用** MINIMUM_TIME_BETWEEN_UPDATES ** 30mts .i当纬度和经度值发生变化时

更新

public class MainActivity extends Activity implements LocationListener {
final DBAdapter1 db=new DBAdapter1(this);
    private ConnectivityReceiver receiver = null;
    private TextView txtNetworkInfo ;
    private static TextView latituteField;
    private static TextView longitudeField;
    private LocationManager locationManager;
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
      private static final String HostUrl =" http://xxx/Service.svc";
     // private static final String HostUrl ="  http://yyyService.svc";
      private static final String NAMESPACE = "http://tempuri.org/";
      private HttpTransportSE httpTransport = new HttpTransportSE(HostUrl);
    private String provider;
    private SoapObject request=null;
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1800000; // in Milliseconds

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    latituteField = (TextView) findViewById(R.id.TextView02);
    longitudeField = (TextView) findViewById(R.id.TextView04);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    Log.i("ConnTest",locationManager.toString());
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

// Initialize the location fields
if (location != null) {
    System.out.println("Provider " + provider + " has been selected.");
    float lat = (float) (location.getLatitude());
    float lng = (float) (location.getLongitude());
    latituteField.setText(String.valueOf(lat));
    longitudeField.setText(String.valueOf(lng));

} else {
    latituteField.setText("provider not available");
    longitudeField.setText("provider not available");
}

    txtNetworkInfo = (TextView)findViewById(R.id.txtNetworkInfo);

    receiver = new ConnectivityReceiver();

            registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));


}
@Override
protected void onResume() {
    super.onResume();
    //locationManager.requestLocationUpdates(provider,1000, 1, this);
    locationManager.requestLocationUpdates(
            provider, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            this
    );
}

/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    float lat = (float) (location.getLatitude());
    float lng = (float) (location.getLongitude());
    longitudeField.setText(String.valueOf(lng));
    latituteField.setText(String.valueOf(lat));

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Disenabled provider " + provider,
            Toast.LENGTH_SHORT).show();

}
protected void Display(Cursor c) {
    Toast.makeText(this, "rowid: " + c.getString(0) + "\n" +
     "Latitude: " + c.getString(1) + "\n" + "Longitude: " + c.getString(2) + "\n" +
     Toast.LENGTH_LONG, 0).show();    
}

@Override
    protected void onDestroy() {
            unregisterReceiver(receiver);

            super.onDestroy();
    }

private String getNetworkStateString(NetworkInfo.State state){
    String stateString = "Unknown";

    switch(state)
    {
            case CONNECTED:         stateString = "Connected";              break;
            case CONNECTING:        stateString = "Connecting";     break;
            case DISCONNECTED:      stateString = "Disconnected";   break;
            case DISCONNECTING:     stateString = "Disconnecting";  break;
            case SUSPENDED:         stateString = "Suspended";              break;
            default:                        stateString = "Unknown";                break;
    }

    return stateString;
}

    private class ConnectivityReceiver extends BroadcastReceiver{

            private Timer mTimer;
            private TimerTask mTimerTask;

            @Override
            public void onReceive(Context context, Intent intent) {
                    NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

                    if(null != info)
                    {
                            String state = getNetworkStateString(info.getState());
                            if(state.equals("Connected")){
                                    try{
                                        mTimer = new Timer();
                                        mTimer.scheduleAtFixedRate(mTimerTask,1000,1800000);
                                        mTimerTask = new TimerTask() {

                                            @Override
                                            public void run() {
                                                SoapPrimitive response=null;
                                                 final String methodname="InsertAllGPSInformation";
                                                    request = new SoapObject(NAMESPACE,methodname);
                                                    envelope.dotNet = true;
                                                    request.addProperty("Longitude",longitudeField.getText().toString()); 
                                                    request.addProperty("Latitude",latituteField.getText().toString()); 
                                                    request.addProperty("Date",newtime);

                                                    envelope.setOutputSoapObject(request);
                                                     String result = null;
                                                    try
                                                     {          
                                                        httpTransport.call(NAMESPACE+"IService/"+methodname, envelope);
                                                        response = ( SoapPrimitive )envelope.getResponse();
                                                        result=response.toString();
                                                     }
                                                    catch(Exception e)
                                                     {
                                                        Toast.makeText(getBaseContext(), "Your Net Connected or Not Login to Net"+"", Toast.LENGTH_LONG).show();
                                                        Log.e("Upload Picture Error:",e.getMessage());
                                                     }
                                                                                                 }
                                        };
                                    }
                                    catch(Exception e)
                                     {
                                        Toast.makeText(getBaseContext(),e.getMessage()+"", Toast.LENGTH_LONG).show();
                                        Log.e("Upload Picture Error:",e.getMessage());
                                     }

2 个答案:

答案 0 :(得分:0)

我想问题是“我为什么每30分钟获得一次更新?”:

然后答案是:“通知的最小时间间隔,以毫秒为单位。此字段仅用作节省电力的提示,位置更新之间的实际时间可能大于或小于此值。” 见http://developer.android.com/reference/android/location/LocationManager.html

或者,您可以使用处理程序或每隔30'触发一次警报,并在警报触发时请求单个位置更新。从API 9开始,有一个requestSingleUpdate()。

答案 1 :(得分:0)

使用Alarm Manager。因为你的计时器可能会死但是闹钟会唤醒你的应用。试试这个工作代码:它每10分钟唤醒CPU并显示通知。

添加到Manifest.xml:

...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver  android:process=":remote" android:name="Alarm"></receiver>
...

代码:

public class Alarm extends BroadcastReceiver 
{    
     @Override
     public void onReceive(Context context, Intent intent) 
     {   
         PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
         wl.acquire();

     // Put here YOUR code.
     Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

     wl.release();
 }

 public void SetAlarm(Context context)
 {
     AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
     Intent i = new Intent(context, Alarm.class);
     PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
     am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
 }

 public void CancelAlarm(Context context)
 {
     Intent intent = new Intent(context, Alarm.class);
     PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
     alarmManager.cancel(sender);
 }
}