Android Shake(Sensor) Service For shake Detection in Application Background

心已入冬 提交于 2019-12-04 14:57:17

I have created this type of functionality in my application https://play.google.com/store/apps/details?id=com.deep.profilemaper .

To achieve this functionality you just have to create background service with returning flag START_STICKY in onStartCommand() method of service. This service restart if someone kill your service.

    public int onStartCommand (Intent intent, int flags, int startId)
    {
        super.onStartCommand(intent, flags, startId);

        //your code here

        return START_STICKY;

    }

It is just demo.

shake event after killed app:

compile 'com.squareup:seismic:1.0.2'

public class serviceShake extends Service implements ShakeDetector.Listener {
    @Override

    public void onCreate() {
        super.onCreate();
        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        ShakeDetector sd = new ShakeDetector(this);
        sd.start(sensorManager);
//register your sensor manager listener here
    }

    @Override
    public void onDestroy() {
//unregister your listener here
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void hearShake() {
        Context ctx = this; // or you can replace **'this'** with your **ActivityName.this**
        try {
            Intent i = ctx.getPackageManager().getLaunchIntentForPackage("com.vyaapaarsamachar");
            ctx.startActivity(i);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO Auto-generated catch block
        }
        Toast.makeText(this, "ShackFromService", Toast.LENGTH_SHORT).show();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!