在后台运行应用程序

时间:2013-03-11 09:53:36

标签: android accelerometer android-sensors

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类完成但是一个初学者我不知道如何实现它。有没有其他方法可以做到这一点?任何人都可以帮我解决

1 个答案:

答案 0 :(得分: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); }

}

请按此link获取更多信息