Android Broadcast Receiver is not working in background

心不动则不痛 提交于 2020-05-14 07:40:08

问题


I have 2 Android mobile cellphones with different Android versions. The first cellphone is running Kitkat and the second one Nougat. I'm currently using the following code. After 5 or 7 hours the android application is not detecting events anymore. Can someone please help me out?

package com.doct.patients.Broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class smsReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"You Got 1 new Sms", Toast.LENGTH_SHORT).show();
    }
}

Android AndroidManifest.xml file below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.doct.patients">
    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true" />

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


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SetupActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait" >
        </activity>

        <receiver android:name=".Broadcast.smsReceiver">
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

回答1:


You need to add android:permission="android.permission.BROADCAST_SMS". So it will be something like this:

<receiver
    android:name="Broadcast.smsReceiver"
    android:permission="android.permission.BROADCAST_SMS">
  <intent-filter android:priority="1000">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>


来源:https://stackoverflow.com/questions/49224341/android-broadcast-receiver-is-not-working-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!