I am working on an app in which "when my app is running and user presses power button" to lock the phone, then before locking it should play a sound.
I have searched for how to do this on SO on following links but didn't get any working solution: Want to Access Power Button events in android
Disable Screen Lock(Power) Button in Android
Override Power button just like Home button
How to hook into the Power button in Android?
I don't want to work with long press on power button. I just want to play my own music when the app/activity is running & user presses power button to lock the phone.
Here is my code what I've done so far:
AndroidManifest.xml
<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java
package com.example.lockunlocksound;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
public class MainActivity extends Activity {
static MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
// Do something here...
mp= MediaPlayer.create(this, R.raw.click123);
mp.start();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Some posts which i've mentioned above claims to work with this, but i am not getting desired output. Where am i wrong ? My phone is just getting locked without playing sound. suggest me how should i go ahead in order to solve this ?