0
package com.example.shake;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {
  private SensorManager sensorManager;
  private boolean color = false;
  private View view;
  private long lastUpdate;

/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    view = findViewById(R.id.textView);
    view.setBackgroundColor(Color.GREEN);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    lastUpdate = System.currentTimeMillis();
  }

  @Override
  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      getAccelerometer(event);
    }

  }

  private void getAccelerometer(SensorEvent event) {
    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];
    double latitude=0;
    double longitude=0;
    String location_message;
    GPSTracker gps;

    float accelationSquareRoot = (x * x + y * y + z * z)
        / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
    long actualTime = System.currentTimeMillis();
    if (accelationSquareRoot >= 2.4) //
    {
      if (actualTime - lastUpdate < 200) {
        return;
      }
      lastUpdate = actualTime;
      gps=new GPSTracker(MainActivity.this);
      if(gps.canGetLocation()){    
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        // \n is for new line
        //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();  
        Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
        try{
         List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
         location_message= addresses.get(0).getLocality();
        if (addresses.size() > 0) 
        {
            Toast.makeText(getApplicationContext(), "Your Location is "     +addresses.get(0).getLocality()
            , Toast.LENGTH_LONG).show();
        }
        }catch(Exception e)
        {
            System.out.print(e);
        }
    }else{
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        Toast.makeText(getApplicationContext(), "Switch on gps"
                , Toast.LENGTH_LONG).show();
        gps.showSettingsAlert();
    }


      /*Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
          .show();
      if (color) {
        view.setBackgroundColor(Color.GREEN);

      } else {
        view.setBackgroundColor(Color.RED);
      }*/
      color = !color;
    }
   }

  @Override
       public void onAccuracyChanged(Sensor sensor, int accuracy) {

   }

  @Override
  protected void onResume() {
    super.onResume();
    // register this class as a listener for the orientation and
    // accelerometer sensors
    sensorManager.registerListener(this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    // unregister listener
    super.onPause();
    sensorManager.unregisterListener(this);
   }
} 

这段代码给出了摇动手机时的当前位置。我想创建一个在后台监控摇动参数并自动显示位置的应用程序。我知道这可以通过 android 中的 Service 类来完成,但作为初学者我不知道怎么实现。还有其他方法吗?谁能帮帮我

4

1 回答 1

1

查看此示例代码:您需要如图所示实现侦听器。

public class Accelerometer extends Service implements AccelerometerListener{ private static 
Context CONTEXT;

@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}

@Override
public void onCreate() {
System.out.println(”start listening”);
// if (AccelerometerManager.isSupported()) { AccelerometerManager.startListening(this);

// }
}

@Override
public void onDestroy() {
System.out.println(”stop listening”);
// if (AccelerometerManager.isListening()) { AccelerometerManager.stopListening();
// }
}



/**
* onShake callback
*/
public void onShake(float force) {
Toast.makeText(this, “Phone shaked omha ya 3ammi el7ag: ” + force,             1000).show(); }

/**
* onAccelerationChanged callback
*/
public void onAccelerationChanged(float x, float y, float z) { System.out.println(”x =     “+x+” y = “+y+” z = “+z); }

}

请点击此链接获取更多信息

于 2013-03-11T10:26:34.513 回答