1
我目前正试图弄清楚,如何在android中获取屏幕开/关事件。目前,只要MainActivity处于运行状态,它就会工作。但是,只要我关闭活动,不知何故服务器和接收器停止工作(我没有得到任何日志消息了)。我想这个问题与某种接收机的动态注册有关。只要应用程序关闭,接收器就会取消注册(?)。我怎样才能保持接收器活着? (在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>
我缺少的东西让我的服务还活着吗?我希望有人能帮助我。
看一看[这里](http://stackoverflow.com/questions/8713361/keep-a-service-running-even-when -phone-是-睡着)。 –
嘿史蒂夫,我想这不能解决我的问题(如果我没有误解某件事情):问题不在于我的服务在睡眠事件中停止运行,更多的是接收器不再工作。我猜想在关闭应用程序后它会被取消注册。 – DonMushroom
嘿史蒂夫再次,对不起,我错了。它确实帮了我很多:D – DonMushroom