[英]Get screen on/off event while application is not running
我目前正在嘗試弄清楚如何在android中打開/關閉屏幕事件。 當前,只要我的MainActivity是runnig,它就可以工作。 但是,一旦我關閉活動,Sevice和Receiver就會以某種方式停止工作(我不再收到任何Log消息)。 我想這個問題與接收器的動態配准有關。 一旦應用程序關閉,接收方便會取消注冊(?)。 如何使接收器保持生命? (不可能在清單文件中聲明接收者)。
我得到以下代碼:
主要活動:
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>
我是否缺少某些東西來使我的服務保持活力? 我希望有人能幫助我。
嘗試使用服務中的完整路徑,如果有的話也可以接收
<service
android:name="ch.ethz.inf.thesis.screenonoffproject.app.ScreenOnOffService">
</service>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.