我目前正在试图找出,如何在Android中获取屏幕开/关事件。目前,只要我的MainActivity运行,它就可以工作。但是一旦我关闭活动,Sevice和Receiver就会停止工作(我不再收到任何Log消息)。我想这个问题,在某种程度上与接收器的动态注册有关。一旦应用程序关闭,接收器就会被取消注册(?)。如何让接收器保持活力? (无法在Manifest文件中声明接收器。)
我收到了以下代码:
主要活动:
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));
}
}
ScreenReceiver:
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 ");}
}
}
ScreenOnOffService:
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>
我错过了让我的服务保持活力的东西吗?我希望有人可以帮助我。
答案 0 :(得分:0)
尝试使用完整路径进行服务并接收(如果有)
<service
android:name="ch.ethz.inf.thesis.screenonoffproject.app.ScreenOnOffService">
</service>