小编Ste*_*oid的帖子

当应用程序在后台时接收短信的 Android 服务

我是 Stackoverflow 的新手,目前正在开发一个处理传入 SMS 的应用程序。在我寻找解决方案时,我遇到了不同的方法,包括工作正常的独立广播接收器和服务。目标是即使在应用程序处于后台且屏幕关闭(手机锁定)时也能接收短信。

我目前的问题是:我收到任何在服务中运行的广播接收器的短信。此服务在我的 MainActivity 的 onResume() 中启动,不应停止。

  • 当我的应用程序在前台时,接收器可以识别所有短信。
  • 即使应用程序在后台但我的手机仍在运行,我也可以收到这些消息。

奇怪的事情发生在这里:

  • 应用程序在前台,我关闭了屏幕 --> 短信被识别。
  • 应用程序在后台,我关闭了屏幕 --> 无法识别短信。

这是我的服务级代码:

public class SmsProcessService extends Service {
    SmsReceiver smsReceiver = new SmsReceiver();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        registerReceiver(smsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

        return START_STICKY;
    }

    private class SmsReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String telnr = "", nachricht = "";

            Bundle extras …
Run Code Online (Sandbox Code Playgroud)

service sms android background broadcastreceiver

6
推荐指数
1
解决办法
9483
查看次数

标签 统计

android ×1

background ×1

broadcastreceiver ×1

service ×1

sms ×1