在Android中关闭应用程序后接收短信 [英] Receive SMS after closing App in Android

查看:119
本文介绍了在Android中关闭应用程序后接收短信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读传入的SMS.我为此使用BroadcastReceiver.它工作正常,但当应用程序关闭时,BroadcastReceiver也会关闭. 这是我正在使用的代码. 清单

I need to read incoming SMS. I'm using BroadcastReceiver for this. It's working fine but when app is closed BroadcastReceiver also close. Here is code that I'm using. Manifest

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

<!--other code -->
<receiver android:name=".IncomingSms">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

传入短信

public class IncomingSms extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

@Override
public void onReceive(Context context, Intent intent) {
    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                String senderNum = phoneNumber;
                String message = currentMessage.getDisplayMessageBody();

                Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);


                // Show Alert
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context,
                        "senderNum: "+ senderNum + ", message: " + message, duration);
                toast.show();

            } // end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" +e);

    }
}
}

该代码运行正常,但希望它运行,即使App已关闭.我想随时阅读SMS.表示此广播运行生命周期永远不会关闭,直到卸载App.我想我需要为此服务,但是我该怎么办呢?我是android的新手.

The code is working fine but want it to run even App is closed. I want to read SMS whenever it come. means this broadcast run lifetime never close until App uninstall. I think I need service for this but how can I do that, I'm new in android.

推荐答案

为此,您需要编写 IntentService ,您可以在广播接收器中启动此类服务,因为广播接收器无法长时间执行

Yo need to write IntentService for that, you can start such service in broadcast receiver, because broadcast reciever can not execute for long time.

这篇关于在Android中关闭应用程序后接收短信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆