我想实现一个处理屏幕开/关的服务。为此,我创建BootReceiver
了在启动完成时调用并在我启动服务的过程中。但是,我ScreenBroadcastReceiver
的从来没有被调用过,为什么?我是不是在错误的地方注册了它,我是在服务的创建上做的...请帮助我应该在哪里注册它?
因此,应用程序应该在后台运行(没有用户交互),它会记录屏幕的开启和关闭活动。我已经启动了这些代码,但似乎我需要注册我的 ScreenBroadcastReceiver 广播接收器。如果我这样做 onCreate 的服务。我应该改变它吗?我的最终目标是在后台运行这个应用程序,这样应用程序就可以在没有用户交互的情况下工作
这是一开始就调用的 BootReceiver:
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("TAG", "BootReceiver");
Intent service = new Intent(context, ScreenListenerService.class);
context.startService(service);
}
}
这是服务:
public class ScreenListenerService extends Service {
public void onCreate(){
super.onCreate();
Log.w("TAG", "ScreenListenerService---OnCreate ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
registerReceiver(screenOnReceiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("TAG", "ScreenListenerService---onStart ");
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
这是 ScreenBroadcastReceiver:
public class ScreenBroadcastReceiver extends BroadcastReceiver {
///this part is never called, even if the screen is turned on/off.
public static boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
System.out.println("SCREEN TURNED ON on BroadcastReceiver");
}
Intent i = new Intent(context, ScreenListenerService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
和清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".main"
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=".ScreenListenerService"></service>
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE" />
</intent-filter>
</receiver>
</application>
</manifest>
更新: 可以在模拟器中测试这段代码并让我知道结果吗?