移动屏幕锁定时不会触发广播接收器

时间:2012-10-10 13:38:17

标签: android broadcastreceiver

当我安装应用程序时,一切正常。我每次发送消息时都可以打印消息正文,直到我锁定移动屏幕。之后,该应用程序停止打印传入的消息。我尝试了很多方法来克服这个问题,但没有运气。请帮帮我......

public class SmsReceiveActivity extends Activity{

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);

receiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(SMS_RECEIVED)) {
Object[] pdus = (Object[]) bundle.get("pdus");
final android.telephony.SmsMessage[] messages = new android.telephony.SmsMessage[pdus.length];

for (int i = 0; i < pdus.length; i++) {
    messages[i] = android.telephony.SmsMessage.createFromPdu((byte[]) pdus[i]);
    incomingMsgString += messages[i].getMessageBody().toString();
   }
    // Print Incoming message Body
  }
 }
}        
  getApplication().registerReceiver(receiver, new IntentFilter(SMS_RECEIVED));
 }
}

2 个答案:

答案 0 :(得分:3)

根据BroadcastReceiver docs,当您使用registerReceiver()注册接收者时,“暂停时您将不会收到意图”。如果您希望接收器独立于您的活动,则应将其实现为命名类并将其发布到清单中。例如,使用匿名BroadcastReceiver

创建命名类
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(SMS_RECEIVED)) {
Object[] pdus = (Object[]) bundle.get("pdus");
final android.telephony.SmsMessage[] messages = new android.telephony.SmsMessage[pdus.length];

for (int i = 0; i < pdus.length; i++) {
    messages[i] = android.telephony.SmsMessage.createFromPdu((byte[]) pdus[i]);
    incomingMsgString += messages[i].getMessageBody().toString();
   }
    // Print Incoming message Body
  }
 }
} 

在您的清单中,在application标记

中添加接收器
    <receiver android:name=".MyReceiver" >
    <intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED"/ >
    </intent-filter>
    </receiver>

然后,当收到短信时,将调用onReceive方法。在那里,您可以打包所需的信息,并向ActivityService发送意图,以便进一步处理。

答案 1 :(得分:0)

将您的广播创建为静态内部类,并在清单中注册。试试这个链接。 Receiver as inner class in Android