在Android中关闭App后收到短信

时间:2017-03-24 07:38:19

标签: android broadcastreceiver android-service

我需要阅读收到的短信。我正在使用BroadcastReceiver。它工作正常,但当应用关闭时BroadcastReceiver也关闭。 这是我正在使用的代码。 的清单

 <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>

IncomingSms

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已关闭。无论什么时候我想阅读短信。表示此广播运行生命周期永远不会关闭,直到卸载我想我需要为此服务,但我怎么能这样做,我是android的新手。

1 个答案:

答案 0 :(得分:0)

你需要写 IntentService ,你可以在广播接收器中启动这样的服务,因为广播接收器不能长时间执行。