在后台锁定和解锁检测

时间:2017-09-11 05:41:46

标签: android screen-lock

我正在开发一款Android应用,我需要检测用户锁定和解锁的时间,而不是屏幕开/关。所以,我可以根据锁定和解锁执行某些操作。但我无法实现目标。

我在服务中声明广播,在清单中注册服务和接收者以及操作。

当应用程序打开时,它工作正常。随着应用程序进入后台,它将停止工作。

public class UseService extends Service {

@Nullable
Vibrator vibr;
MediaPlayer audi;

//This is Service Class
@Override
public IBinder onBind(Intent intent) {

    return null;
    }




public void onCreate() {

    super.onCreate();






    IntentFilter filter = new IntentFilter();

    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction("android.intent.action.SCREEN_ON");
    registerReceiver(receiver, filter);
}

//Broadcast Receiver

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

        if (action.equals(Intent.ACTION_SCREEN_OFF) && myKM.inKeyguardRestrictedInputMode())
        {

            vibr.vibrate(500);


            if( action.equals(Intent.ACTION_SCREEN_ON) &&  !myKM.inKeyguardRestrictedInputMode()  )
            {

                vibr.vibrate(5000);

            }

        }
    }
};



//************************Started*************
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    audi=MediaPlayer.create(UseService.this, R.raw.start);
    Toast.makeText(UseService.this, "The Service Has Been Started",Toast.LENGTH_SHORT).show();

    return START_STICKY;
}


//*******************OnDestroy****************
@Override
public void onDestroy() {
    Toast.makeText(UseService.this, "The Service is Destroyed",Toast.LENGTH_SHORT).show();
    unregisterReceiver(receiver);


}


}

主要活动

public class MainActivity extends AppCompatActivity {


Vibrator vibr;
Button btns;

//this is MainActivity 

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btns=(Button)findViewById(R.id.btn);
    vibr=(Vibrator) getSystemService(VIBRATOR_SERVICE);


    btns.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(getApplicationContext(), UseService.class);
            startService(intent);

        }
    });

}

@Override
protected void onPause() {
    super.onPause();

}
}

0 个答案:

没有答案