【问题标题】:BroadcastReceiver to detect screen on/off and Service not workingBroadcastReceiver 检测屏幕开/关和服务不工作
【发布时间】:2016-10-24 12:28:28
【问题描述】:

我有一个简单的BroadcastReceiver,它可以检测我的屏幕何时关闭打开。我正在使用 Service 而不是 Activity。我试过在Android 4.4.2 API 19Android 6.0 API 23 上运行该服务。

我做错了什么?

此外,根据 StackOverflow 和 ThinkAndroid 的许多回答,您不应该在 AndroidManifest 中添加服务。

public class BackgroundService extends Service {

@Override
public void onCreate() {
    super.onCreate();
    // REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver mReceiver = new ScreenReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    boolean screenOn = intent.getBooleanExtra("screen_state", false);
    if (!screenOn) {
        System.out.println("SCREEN OFF");
    } else {
        System.out.println("SCREEN ON");
    }
    return START_NOT_STICKY;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

我的广播接收器

public class ScreenReceiver extends BroadcastReceiver {

private boolean screenOff;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        screenOff = false;
    }
    Intent i = new Intent(context, BackgroundService.class);
    i.putExtra("screen_state", screenOff);
    context.startService(i);
  }
}

我的 AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dahlstore.sosbackground2">

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service
            android:name=".BackgroundService"
            android:enabled="true"
            android:exported="false" />

        <receiver
            android:name=".ScreenReceiver"
            android:enabled="true"
            android:exported="true"></receiver>

    </application>

</manifest>

Logcat

10-24 15:01:00.122 762-762/com.android.systemui E/KeyguardUpdateMonitor: Object tried to add another callback

java.lang.Exception: Called by
    at com.android.keyguard.KeyguardUpdateMonitor.registerCallback(KeyguardUpdateMonitor.java:1104)
    at com.android.keyguard.KeyguardSelectorView.onResume(KeyguardSelectorView.java:347)
    at com.android.keyguard.KeyguardHostView.onScreenTurnedOn(KeyguardHostView.java:1458)
    at com.android.keyguard.KeyguardViewManager.onScreenTurnedOn(KeyguardViewManager.java:500)
    at com.android.keyguard.KeyguardViewMediator.handleNotifyScreenOn(KeyguardViewMediator.java:1960)
    at com.android.keyguard.KeyguardViewMediator.access$2900(KeyguardViewMediator.java:126)
    at com.android.keyguard.KeyguardViewMediator$5.handleMessage(KeyguardViewMediator.java:1601)
    at android.os.Handler.dispatchMessage(Handler.java:110)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:5368)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
    at dalvik.system.NativeStart.main(Native Method)

根据 VOLACON_SECRET 更改后更新的 LOGCAT

10-24 17:00:32.441 12822-12822/? E/cutils-trace: Error opening trace file: 

No such file or directory (2)
10-24 17:00:32.663 12822-12822/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-24 17:00:32.663 12822-12822/? E/android.os.Debug: failed to load memtrack module: -2
10-24 17:00:36.773 138-744/? E/AudioMTKHardware: setCommonParameters() still have param.size() = 1, remain param = "screen_state=on"
10-24 17:00:37.802 1002-12848/com.microsoft.launcher E/Item: java.sql.SQLException: Unable to run insert stmt on object ms.loop.lib.profile.Application@42a65780: INSERT INTO `application` (`applicationInstalledAt` ,`applicationLastUsedAt` ,`applicationName` ,`applicationUninstalledAt` ,`applicationUpdatedAt` ,`deviceId` ,`locationLabel` ,`packageName` ,`annotations` ,`updatedAt` ,`changedAt` ,`createdAt` ,`entityId` ,`score` ,`persist` ,`createSignalSent` ,`annotationsChanged` ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
10-24 17:00:40.124 1053-1053/com.google.process.gapps E/NetworkScheduler.SR: Invalid parameter app
10-24 17:00:40.124 1053-1053/com.google.process.gapps E/NetworkScheduler.SR: Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
10-24 17:00:41.684 1067-3062/com.google.android.gms E/Drive.UninstallOperation: Package still installed com.dahlstore.sosbackground2
10-24 17:00:41.923 138-18033/? E/AudioMTKHardware: setCommonParameters() still have param.size() = 1, remain param = "screen_state=off"
10-24 17:00:42.026 1067-12852/com.google.android.gms E/IntentOperationSvc: Failed to instantiate Chimera operation impl, dropping operation
10-24 17:00:42.027 6694-6694/com.android.vending E/Finsky: [1] com.google.android.finsky.wear.bo.a(836): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
10-24 17:00:42.278 1053-1053/com.google.process.gapps E/NetworkScheduler.SR: Invalid parameter app
10-24 17:00:42.278 1053-1053/com.google.process.gapps E/NetworkScheduler.SR: Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
10-24 17:00:43.576 12905-12905/com.whatsapp E/dalvikvm: Could not find class 'android.support.v4.app.g', referenced from method android.support.v4.app.ab.a

我的 build.gradle(模块:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"

defaultConfig {
    applicationId "com.dahlstore.sosbackground2"
    minSdkVersion 15
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
}

【问题讨论】:

  • 我在一些问题中读到SCREEN_OFF 是受保护的广播,广播接收器需要动态注册它而不是在清单中。你能解决问题吗?

标签: android android-intent broadcastreceiver android-gradle-plugin android-service


【解决方案1】:

如上所述,您应该在清单中包含 Service 和 BroadcastReceiver。但是,您在 Service 中动态注册您的 BroadCastReceiver 并且永远不会取消注册它。 如果你想一直接收通知,你应该在清单中注册接收器并使用相应的internt过滤器。 或者,在 Service 的 onTerminate() 方法中注销接收者。

【讨论】:

  • 好的,所以我的 IntentFilter 过滤器 = new IntentFilter(Intent.ACTION_SCREEN_ON);不做同样的工作?
  • 这个问题认为你不应该在清单中使用它
  • 可以在manifest中使用,也可以在服务启动时动态注册和注销广播接收器(服务运行时才会通知)
  • 如果你想一直接收事件,不管你的Service是否在运行,在manifest中声明receiver,否则动态注册和注销。这是教程:vogella.com/tutorials/AndroidBroadcastReceiver/article.html
【解决方案2】:

你需要在清单中包含服务和接收者......就像那样

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dahlstore.sosbackground">
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

  <service android:name=".BackgroundService"/>

  <receiver android:name=".ScreenReceiver" >
        <intent-filter>
         <action android:name="android.intent.action.SCREEN_OFF"/>
         <action android:name="android.intent.action.SCREEN_ON"/>
        </intent-filter>
    </receiver>

</application>
</manifest>

嘿试试这个广播接收器.......

public class ScreenReceiver extends BroadcastReceiver {

private boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Log.i("[BroadcastReceiver]", "MyReceiver");

    if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
        Log.i("[BroadcastReceiver]", "Screen ON");
    }
    else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
        Log.i("[BroadcastReceiver]", "Screen OFF");
       }
     Intent i = new Intent(context, BackgroundService.class);
     i.putExtra("screen_state", screenOff);
     context.startService(i);
    }
  }

【讨论】:

  • 非常感谢!根据您的建议,我现在已经更改了问题中的代码,但它仍然会引发异常,正如您在新的 logcat 中看到的那样。
  • 感谢上帝!现在我得到了一个更合理的 logcat.. 我会试着找出我应该在哪里使用 PendingIntent.. 或者你现在已经?
  • 我看到您已经制作了自己的项目来帮助我,非常感谢!不幸的是,它在我的模拟器、我的 S7 Edge (Android 6.0.1) 或我的未知品牌手机 (Android 4.4.2) 上都不起作用。我正在再次上传最新的 logcat。我不确定这是否可能是由于我使用 Android Studio 造成的。也许我应该下载并尝试 Eclipse。既然您有该项目的工作示例,您可以将其发送给我吗?
  • 我想我现在知道问题所在了。当我多次锁定/解锁屏幕时,我收到以下错误:E/KeyguardUpdateMonitor: Object 试图添加另一个回调 java.lang.Exception: Called by 你认为 keyguard 试图阻止我让接收器工作吗?
  • @Secret_Volcano 当您传入 putExtra 时,您没有更改变量 screenOff。
猜你喜欢
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 2019-08-12
  • 1970-01-01
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多