java - 应用程序未运行时获取屏幕开/关事件

标签 java android android-event

我目前正在尝试弄清楚如何在android中获取屏幕开/关事件。目前,只要我的 MainActivity 正在运行,它就可以工作。但是,一旦我关闭 Activity ,服务和接收器就会以某种方式停止工作(我不再收到任何日志消息)。我想这个问题在某种程度上与接收器的动态注册有关。一旦应用程序关闭,接收者就会被取消注册(?)。我怎样才能让接收者保持活力? (无法在 Manifest 文件中声明接收者)。

我得到了以下代码:

主要 Activity :

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));
    }
}

屏幕接收器:

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 ");}
    }
}

屏幕开启关闭服务:

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>

关于java - 应用程序未运行时获取屏幕开/关事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405084/

相关文章:

java - 未找到 Android Google Play 服务视觉条码扫描器库

android - 单击其子项时更改父项的背景颜色

android - LinkedIn 集成 Android 移动 SDK 电子邮件 ID 未获取

java - 在服务器中更改样式后,Android 网页未更新

java - Android - "Faking"触摸事件不起作用

android - 如何在backpress时退出android应用程序?

java - 为什么这种(​​错误)使用 Java 泛型的方法无法编译?

java - 无法使用简单的java代码进行selenium浏览器自动化的下一个注释

java - 如何在 JSP 中将 JavaScript 值传递给 Scriptlet?

java - 格式化程序格式化方法输出限制?