英文:
Broadcast receiver not working in background
问题
我正在创建一个应用程序,该应用程序可以检测到安卓手机上的即将到来的短信,但是该应用程序在后台不起作用。
这是我的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, "Thank you for granting access", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "No problem", Toast.LENGTH_LONG).show();
}
}
}
}
}
这是MyReceiver.java文件,我在其中检测即将到来的短信并显示消息的Toast。
当应用程序打开时,它可以正常工作,但当我退出应用程序时,它无法检测到任何短信。
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) {
Log.i(TAG, "Intent Received: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle dataBundle = intent.getExtras();
if (dataBundle != null) {
Object[] pdus = (Object[]) dataBundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = dataBundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
} else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
msg = messages[i].getMessageBody();
phoneNo = messages[i].getOriginatingAddress();
}
Toast.makeText(context, "Message: " + msg + "\nNumber: " + phoneNo, Toast.LENGTH_SHORT).show();
}
}
}
}
请告诉我是否存在任何错误。
<details>
<summary>英文:</summary>
I am creating a app which can detetct incomming sms to android phone but app is not working in background.
Here is my mainactivity.java in which i am asking for the permission from user to allow access to read sms.
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.
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.
</details>
# 答案1
**得分**: -1
请确保在您的 Android Mainfest.xml 文件中包含以下内容:
```xml
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
还需要添加以下内容:
<receiver
android:name="com.example.times.MyReceiver"
android:enabled="true"
android:exported="true">
</receiver>
编辑:
在您的应用关闭或在后台运行时,您需要一个 Intent Service 来读取短信。
Intent Service - 在后台运行
步骤:
- 创建 Intent Service
- 将其添加到清单文件中
- 通过 Intent 在您的广播接收器的 onReceive() 方法中调用它
英文:
Make sure you have these in your 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 <br>
You need an Intent Service to read sms while your app is closed or in background.<br>
Intent Service - Run in Background
Steps:
- Create Intent Service
- Add it Manifest
- Call it from your Broadcast Receiver onReceive() method via Intent
专注分享java语言的经验与见解,让所有开发者获益!
评论