仅在运行中的活动时接收SMS消息

时间:2015-02-17 10:54:54

标签: android crash sms manifest

我正在构建一个Android应用程序,它接收SMS消息并从特定的网关/发送者显示它们。

问题是,如果我在AndroidManifest文件中声明接收器,它会一直接收来自所有人的消息,即使应用程序暂停/关闭也是如此。每当我没有在应用程序上收到短信时,这会导致应用程序强制崩溃。

这是我在ReceieveMessage.java中的代码

package com.phoenix.omnisurf;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class ReceiveMessage extends BroadcastReceiver {

private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static String messageBody = "";

@Override
public void onReceive(Context context, Intent intent) {
    final Bundle bundle = intent.getExtras();
    if (bundle != null) {

        messageBody = "";

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

        for (int i = 0; i < pdus.length; i++) {
            SmsMessage messageHandler = SmsMessage.createFromPdu((byte[]) pdus[i]);
            messageBody += messageHandler.getDisplayMessageBody();
        }

        SurfActivity.mThis.messageContainer.setText(messageBody);
    }
}
}

我还在我的Manifest上注册了以下接收者:

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

    <!-- Message Receiver -->
    <receiver android:name=".ReceiveMessage">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

如何创建仅在特定活动打开或应用程序运行时打开的广播接收器?

2 个答案:

答案 0 :(得分:2)

只需检查您的活动是否在前台

将此添加到您的活动中     private static boolean isInForeground;

onResume(){
 super.onResume();
 isInForground = true;
}

onPause(){
 super.onPause();
 isInForground = false;
}

在你的Receiver班中查看

 if(SurfActivity.isInForeground){
   SurfActivity.mThis.messageContainer.setText(messageBody);
}

答案 1 :(得分:2)

您可以动态注册接收器:

@Override
protected void onResume() {
    super.onResume();
    final IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mBroadcastReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mBroadcastReceiver);
}