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 に答える