简体   繁体   English

广播接收器不在后台工作

[英]Broadcast receiver not working in background

I am creating a app which can detetct incomming sms to android phone but app is not working in background.我正在创建一个应用程序,它可以检测到 android 手机的传入短信,但应用程序无法在后台运行。

Here is my mainactivity.java in which i am asking for the permission from user to allow access to read sms.这是我的 mainactivity.java,我在其中请求用户允许读取短信。

package com.example.times;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final int READ_SMS_PERMISSION=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED)
        {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS))
            {
//                do nothing
            }
            else
            {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, READ_SMS_PERMISSION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
    {
        switch(requestCode)
        {
            case READ_SMS_PERMISSION:
            {
                if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                {
                    Toast.makeText(this, "Thankyou for granting access", Toast.LENGTH_LONG).show();


                }
                else
                {
                    Toast.makeText(this, "No problem", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

Here is myreciver.java in which i am detecting incomming sms and making toast of that msg.这是 myreciver.java,我在其中检测到传入的短信并为该消息敬酒。

When app is opened then it is working properly but when i exit the app it is not detecting any sms.打开应用程序后,它可以正常工作,但是当我退出应用程序时,它没有检测到任何短信。

package com.example.times;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
    private static final String TAG="SmsBroadcastReceiver";

    String msg, phoneNo ="";


    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
//        throw new UnsupportedOperationException("Not yet implemented");

        Log.i(TAG, "Intent Received: " +intent.getAction());


        if (intent.getAction()==SMS_RECEIVED)
        {
            Bundle dataBundle = intent.getExtras();
            if (dataBundle!=null)
            {
                Object[] mypdu=(Object[])dataBundle.get("pdus");
                final SmsMessage[] message = new SmsMessage[mypdu.length];

                for (int i =0; i<mypdu.length; i++)
                {
                    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
                    {
                        String format= dataBundle.getString("format");
                        message[i] = SmsMessage.createFromPdu((byte[])mypdu[i],format);

                    }
                    else
                    {
                        message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i]);
                    }

                    msg =message[i].getMessageBody();
                    phoneNo= message[i].getOriginatingAddress();
                }
                Toast.makeText(context, "Message: " +msg +"\nNumber: " +phoneNo, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Telll me if i am doing something wrong.如果我做错了什么,请告诉我。

Make sure you have these in your Android Mainfest.xml确保你的 Android Mainfest.xml 中有这些

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

And the following以及以下

<receiver
    android:name=
        "com.example.times.MyReceiver"
    android:enabled="true"
    android:exported="true">
</receiver>

EDIT编辑
You need an Intent Service to read sms while your app is closed or in background.当您的应用程序关闭或在后台时,您需要一个 Intent 服务来读取短信。
Intent Service - Run in Background 意图服务 - 在后台运行

Steps:脚步:

  • Create Intent Service创建意图服务
  • Add it Manifest添加它清单
  • Call it from your Broadcast Receiver onReceive() method via Intent通过 Intent 从您的广播接收器 onReceive() 方法调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM