java - 如何在android中继续在后台运行前台服务

标签 java android background android-service

我想在屏幕锁定和后台时通过摇动来打开/关闭应用程序,下面是我的代码,仅在前台运行,你能帮我看看前台服务如何在后台继续运行吗?

MainActivty.java

public class Torchclass extends Activity {

   // The following are used for the shake detection
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
public static Camera cam = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.torchlayout);

    Intent intent = new Intent(Torchclass.this, ShakeService.class);
    startService(intent);

    // ShakeDetector initialization
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetector();
    mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {

        @Override
        public void onShake(int count) {
            try {
                if (getPackageManager().hasSystemFeature(
                        PackageManager.FEATURE_CAMERA_FLASH)) {
                    cam = Camera.open();
                    Parameters p = cam.getParameters();
                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    cam.setParameters(p);
                    cam.startPreview();
                }
            } catch (Exception e) {

                e.printStackTrace();
                Toast.makeText(getBaseContext(), "Exception flashLightOn()",
                        Toast.LENGTH_SHORT).show();

                if (getPackageManager().hasSystemFeature(
                        PackageManager.FEATURE_CAMERA_FLASH)) {
                    cam.stopPreview();
                    cam.release();
                    cam = null;
                }
            }

        }
    });
}

@Override
public void onResume() {
    super.onResume();
    // Add the following line to register the Session Manager Listener onResume
    mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}

@Override
public void onPause() {
    // Add the following line to unregister the Sensor Manager onPause
      mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

    super.onPause();
}
}

ShakeDetector.java

public class ShakeDetector implements SensorEventListener {

/*
 * The gForce that is necessary to register as shake.
 * Must be greater than 1G (one earth gravity unit).
 * You can install "G-Force", by Blake La Pierre
 * from the Google Play Store and run it to see how
 *  many G's it takes to register a shake
 */
private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
private static final int SHAKE_SLOP_TIME_MS = 500;
private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;

private OnShakeListener mListener;
private long mShakeTimestamp;
private int mShakeCount;

public void setOnShakeListener(OnShakeListener listener) {
    this.mListener = listener;
}

public interface OnShakeListener {
    public void onShake(int count);
}

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

@Override
public void onSensorChanged(SensorEvent event) {

    if (mListener != null) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        float gX = x / SensorManager.GRAVITY_EARTH;
        float gY = y / SensorManager.GRAVITY_EARTH;
        float gZ = z / SensorManager.GRAVITY_EARTH;

        // gForce will be close to 1 when there is no movement.
        Float f = new Float(gX * gX + gY * gY + gZ * gZ);
        Double d = Math.sqrt(f.doubleValue());
        float gForce = d.floatValue();

        if (gForce > SHAKE_THRESHOLD_GRAVITY) {
            final long now = System.currentTimeMillis();
            // ignore shake events too close to each other (500ms)
            if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
                return;
            }

            // reset the shake count after 3 seconds of no shakes
            if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
                mShakeCount = 0;
            }

            mShakeTimestamp = now;
            mShakeCount++;

            mListener.onShake(mShakeCount);
        }
    }
}
} 

ShakeService.java

public class ShakeService extends Service {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;

public ShakeService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onCreate() {
    super.onCreate();
    // ShakeDetector initialization
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager
            .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetector();
    mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {

        @Override
        public void onShake(int count) {

            Intent i = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
            getApplicationContext().startActivity(i);

        }
    });
    mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}

@Override
public void onDestroy() {
     mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

    super.onDestroy();
}
}

最佳答案

您应该重写服务中的 onStartCommand 方法:

public int onStartCommand(Intent intent, int flags, int startId) {
{
return START_STICKY
}

关于java - 如何在android中继续在后台运行前台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627349/

相关文章:

java - ASM 字节码库中用于确定操作码性质的实用方法?

java - 列表 size() 上的 ConcurrentModificationException

android - 从 BroadcastReceiver 访问 Activity 实例

android, matcher.appendReplacement(sb, '$8' ) 通过 ArrayIndexOutOfBoundsException

java 设置字母在一定范围内的循环使用

java - 编译程序时出现错误 'void' type not allowed here

java.text.ParseException : Unparseable date: "04-02-2019"

html - CSS - 当 .b :hover? 时,我可以更改 div .a 背景色吗

XXHDPI 的 Android 背景图像大小

android - 当应用程序进入后台时,将数据从 Android 设备发送到服务器