[英]Broadcast receiver not detecting keyevents
我正在嘗試在我的應用中接收電源按鈕事件。 我已經在清單文件中添加了以下代碼,然后在廣播接收器類的receive方法中顯示了吐司,但是該代碼仍然無法正常工作。 我想念什么嗎?
<receiver android:name="com.xxxxx">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</receiver>
問候
是的,您可能想做的只是幾件事,我想清除,在屏幕關閉時顯示烤面包是沒有用的,同時檢測電源按鈕和屏幕狀態是否相同,我將向您展示如何檢測屏幕狀態和顯示烤面包僅,但是電源按鈕我仍然不知道如何檢測它,因為電源按鈕僅由系統管理,我認為您需要root才能調整電源按鈕或向電源按鈕添加功能。 這里是您需要的任何代碼:
1-您需要一項可以啟動/停止檢測屏幕狀態的活動,一項使您的應用在后台運行的服務,最后是Broadcastreceiver。 因此,從活動中您應該開始服務:
startService(new Intent(MainActivity.this, yourservice.class));
確保完成后將其停止
stopService(new Intent(MainActivity.this, yourservice.class));
2-您的服務應如下所示:
public class yourservice extends Service{
private BroadcastReceiver mReceiver;
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
this.mReceiver = new your receiver();
this.registerReceiver(this.mReceiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (yourbroasdcast.screenOff) {
//here screen is off do your stuff
} else {
//here screen is on do your stuff example your toast
Toast.makeText(getApplicationContext(), "write your toast here", Toast.LENGTH_LONG).show();
}
return START_STICKY;
}
3-您的廣泛接收者:
public class yourbroadcast extends BroadcastReceiver{
public static boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
}else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, yourservice.class);
i.putExtra("screen state", screenOff);
context.startService(i);
}
}
4-清單應如下所示
<service
android:enabled="true"
android:name=".yourservice"/>
<receiver android:name=".yourbroadcast" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
希望我能幫助您...如果您需要什么,請問我:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.