ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

android-BroadcastReciever以检测屏幕开/关和服务不起作用

2019-11-18 03:25:53  阅读:275  来源: 互联网

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


我非常需要我的问题的帮助.

我有一个简单的BroadcastReciever,可以用来检测屏幕的打开和关闭时间.我正在使用服务而不是活动.我尝试在Android 4.4.2 API 19和Android 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;
}

我的BroadCastReciever

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(Module: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'
}

解决方法:

如上面的回答所述,您应该在清单中包括Service和BroadcastReceiver.但是,您可以在Service中动态注册BroadCastReceiver,并且永远不要取消注册.
如果您想一直接收通知,则应在清单中注册接收者并带有相应的内部过滤器.
或者,在Service的onTerminate()方法中注销接收器.

标签:android-intent,android-service,broadcastreceiver,android,android-gradle-plugin
来源: https://codeday.me/bug/20191118/2025077.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有