【发布时间】:2017-03-14 06:14:49
【问题描述】:
我正在开发一个应用程序,其中“当我的应用程序正在运行并且用户按下电源按钮”来锁定手机,然后在锁定之前它应该播放声音。
我已经在以下链接上搜索了如何在 SO 上执行此操作,但没有得到任何可行的解决方案: 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?
我不想长按电源按钮。我只想在应用/活动正在运行并且用户按下电源按钮锁定手机时播放我自己的音乐。
这是我到目前为止所做的代码:
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);
}
}
我上面提到的一些帖子声称可以使用它,但我没有得到想要的输出。我哪里错了? 我的手机刚刚被锁定而没有播放声音。 建议我如何解决这个问题?
【问题讨论】:
标签: android event-handling lockscreen onkeydown android-powermanager