我有以下代码 我想检测一下手机的屏幕 但函数onReceive永远不会被调用 有谁能给我一个解决方案。 请帮忙。 如果有人有任何其他工作代码,请帮助。 谢谢
package com.pack;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class Screen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
Context con = this;
this.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Screen off...................");
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
答案 0 :(得分:1)
您的代码适合我。我修改了代码,因此它更容易阅读并添加了一些sysout,但它的工作方式与你的编写方式相同:
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Screen off...................");
}
}, filter);
}
@Override
protected void onResume() {
super.onResume();
System.out.println("onResume()");
}
@Override
protected void onDestroy() {
super.onDestroy();
System.out.println("onDestroy()");
}
@Override
protected void onPause() {
super.onPause();
System.out.println("onPause()");
}
如果我这样做,它会打印以下内容(开始活动,关闭屏幕,打开屏幕,按后退按钮):
onResume()
onPause()
Screen off...................
onResume()
onPause()
onDestroy()
此后活动被销毁,因此不会显示任何事件。也许你想在AndroidManifest中注册你的BroadcastReceiver。