我目前正在尝试弄清楚如何在android中获取屏幕开/关事件。目前,只要我的 MainActivity 正在运行,它就可以工作。但是,一旦我关闭 Activity ,服务和接收器就会以某种方式停止工作(我不再收到任何日志消息)。我想这个问题在某种程度上与接收器的动态注册有关。一旦应用程序关闭,接收者就会被取消注册(?)。我怎样才能让接收者保持活力? (无法在 Manifest 文件中声明接收者)。
我得到了以下代码:
主要 Activity :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getApplicationContext(), ScreenOnOffService.class));
}
}
屏幕接收器:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.e("test","onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("test","Screen Off ");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("test","Screen On ");}
}
}
屏幕开启关闭服务:
public class ScreenOnOffService extends Service {
//Some unimportant code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="ch.ethz.inf.thesis.screenonoffproject.app.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ScreenOnOffService">
</service>
</application>
</manifest>
我是否缺少一些东西来维持我的服务?我希望有人能帮助我。
最佳答案
尝试使用服务和接收器的完整路径(如果有)
<service
android:name="ch.ethz.inf.thesis.screenonoffproject.app.ScreenOnOffService">
</service>
关于java - 应用程序未运行时获取屏幕开/关事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405084/