如何每5分钟发送一条短信,每30秒更新一次

时间:2015-04-12 23:17:46

标签: android timer smsmanager google-client user-location

以下代码将每30秒更新一次用户位置,如果位置大于半径,则进行一些计算,然后将SMS消息发送到电话号码。

我的问题是,如何每5分钟发送一条短信,每隔30秒发一次更新位置?

怎么办呢?有什么建议吗?

  /*
 * Constants for location update parameters
 */
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;

// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 30;///////////////////////////////////////////

// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;

// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS =
        MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;

// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS =
        MILLISECONDS_PER_SECOND * FAST_CEILING_IN_SECONDS;


// A request to connect to Location Services
private LocationRequest mLocationRequest;

/*
 * Note if updates have been turned on. Starts out as "false"; is set to "true" in the
 * method handleRequestSuccess of LocationUpdateReceiver.
 *
 */
boolean mUpdatesRequested = false;


@Override
protected void onCreate(Bundle savedInstanceState) {////////////////////////////////////////////
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_patient__tracing);
    info = (TextView) findViewById(R.id.info);
    if (servicesConnected()) ///////////////////////////////////////////////////////////////////
    {
        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

    }
    // Create a new global location parameters object
    mLocationRequest = LocationRequest.create();

    /*
     * Set the update interval - This acts as minimum which values are requested from the app
     */
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);

    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    // Set the interval ceiling to one second - This acts as maximum which get fed when location is available by other apps
    mLocationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);

    // Note that location updates are off until the user turns them on
    mUpdatesRequested = false;


    ToggleButton button = (ToggleButton) findViewById(R.id.serviceSwitch);

    button.setChecked(mUpdatesRequested);


    button.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton button, boolean isChecked) {


            if (!isChecked) {

                stopPeriodicUpdates();
            } else
                startPeriodicUpdates();

        }
    });


}

/**
 * Verify that Google Play services is available before making a request.
 *
 * @return true if Google Play services is available, otherwise false
 */
private boolean servicesConnected() {

    // Check that Google Play services is available
    int resultCode =
            GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {


        Log.d(this.getClass().getSimpleName(), "available " + "");

        // Continue
        return true;
        // Google Play services was not available for some reason
    } else {

        Log.d(this.getClass().getSimpleName(), "not available " + "");

        return false;
    }
}

/*
 * Called when the Activity is restarted, even before it becomes visible.
 */
@Override
public void onStart() {

    super.onStart();

    /*
     * Connect the client. Don't re-start any requests here;
     * instead, wait for onResume()
     */
    googleApiClient.connect();

}

/*
 * Called when the Activity is no longer visible at all.
 * Stop updates and disconnect.
 */
@Override
public void onStop() {

    stopPeriodicUpdates();
    // After disconnect() is called, the client is considered "dead".
    googleApiClient.disconnect();

    super.onStop();
}


@Override
public void onConnectionFailed(ConnectionResult result) {

    Log.d(this.getClass().getSimpleName(), "onConnectionFailed " + "");
    //TODO inform user there is somehting wrong
}

@Override
public void onConnected(Bundle connectionHint) {


    Log.d(this.getClass().getSimpleName(), "onConnected ");
    //TODO do things here

    getCurrentLocation();
}

private void getCurrentLocation() {

    if (googleApiClient.isConnected()) {
        Location loc = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();
        double alt = loc.getAltitude();
        float acc = loc.getAccuracy();
        long time = loc.getTime();
        String loc_info = "lat: " + lat + " lon: " + lon + " alt: " + alt + " acc: " + acc + " time: " + time;
        Log.d(this.getClass().getSimpleName(), loc_info);

    }


}


/**
 * In response to a request to start updates, send a request
 * to Location Services
 */
private void startPeriodicUpdates() {//////////////////////////////////////////

    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}


@Override
public void onLocationChanged(Location loc) {///////////////////////////
    //Location update
    double lat1=22.762503862128362;// must be at create
    double lon1=39.08618710935116;//must in create take it from main region table
    double lat = loc.getLatitude();
    double lon = loc.getLongitude();
    double alt = loc.getAltitude();
    float acc = loc.getAccuracy();
    long time = loc.getTime();
    String loc_info ="location Chaned lat: " + lat +" lon: " + lon  +" alt: " + alt + " acc: " + acc +" time: " + time;
    Log.d(this.getClass().getSimpleName(), loc_info );
    CalculateDis(lat1,lon1,lat,lon);
    new insertUserTask(lat,lon).execute();
    info.setText(loc_info);





} double raduis=15;

  private void CalculateDis(double lat1,double lon1,double lat2,double lon2){

      double earth_raduis=6371000;//METERS
      double lat1Rad=Math.toRadians(lat1);
      double lat2Rad=Math.toRadians(lat2);
      double diffLongRad=Math.toRadians(lon2-lon1);
      double a=Math.sin(lat1Rad)*Math.sin(lat2Rad);
      double b=Math.cos(lat1Rad)*Math.cos(lat2Rad)*Math.cos(diffLongRad);
      double radDis=Math.acos(a+b);
      double distance=radDis*earth_raduis;
      if (distance>raduis){
          Toast.makeText(getApplicationContext(), "patient out side" , Toast.LENGTH_SHORT).show();

           String phoneNo="0555555555";

          String sms =    "text Sms"  ;

          Toast.makeText(getApplicationContext(), "patient out side" , Toast.LENGTH_SHORT).show();

          try{
          SmsManager smsManager = SmsManager.getDefault();
              ArrayList<String> parts = smsManager.divideMessage(sms);
              smsManager.sendMultipartTextMessage(phoneNo, null, parts, null, null);

              Toast.makeText(getApplicationContext(), "SMS Sent!",
                      Toast.LENGTH_LONG).show();}
          catch (Exception e){
              Toast.makeText(getApplicationContext(),
                      "SMS faild, please try again later!",
                      Toast.LENGTH_LONG).show();
              e.printStackTrace();


          }


      }

      else
          Toast.makeText(getApplicationContext(), "patient in side" , Toast.LENGTH_SHORT).show();



  }

1 个答案:

答案 0 :(得分:0)

基本上你需要CountDownTimer类(可能解决方案的一个实例)。我成功地使用了我自己的项目。我希望它会有所帮助。

public class MyCountDownTimer extends CountDownTimer {
      public MyCountDownTimer(long startTime, long interval) {
       super(startTime, interval);
      }

      @Override
      public void onFinish() {
        //send sms
      }

      @Override
      public void onTick(long millisUntilFinished) {
          long time = millisUntilFinished / 1000;
          Log.v("timer: ", ""+time);
      }
     }

//use it like
private final long startTime = 30 * 1000; //it is 30 second change it for your own requirement
private final long interval = 1 * 1000; // 1 second interval

CountDownTimer cDownTimer = new MyCountDownTimer(startTime, interval);
//and start timer using
cDownTimer.start();
//and stop timer using
cDownTimer.cancel();
 // something like that