BroadCastReceiver强制关闭Sms接收

时间:2010-12-03 17:26:35

标签: android broadcastreceiver

我正在创建一个简单的Android应用程序,它将响应收到的。 我正在使用braodcastreceiver来接收短信。 活动代码是

package com.om;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class MyTest extends Activity {
  public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
  /** Called when the activity is first created. */
  BroadcastReceiver smsReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context _context, Intent _intent) {
      System.out.println("SMS Received");
    }
  };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      IntentFilter filter = new IntentFilter(SMS_RECEIVED);
      registerReceiver(smsReceiver, filter);
  }
}

当我在SDK 2.1 AVD上运行此活动并向该端口发送SMS时,它会强制关闭。 请告诉我代码中的错误。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

嗨,谢谢你的回答 这段代码工作正常

package com.om;

import android.app.Activity;

import android.content.BroadcastReceiver;

import android.content.Context;

导入android.content.Intent;

import android.content.IntentFilter;

导入android.os.Bundle;

导入android.widget.Toast;

导入android.telephony.SmsManager;

导入android.telephony.SmsMessage;

公共类MyTest扩展Activity {     公共类SmsReceiver扩展了BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        Context context = getApplicationContext();
        String msg = "SMS Received.....";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, msg, duration);
        toast.show();

    }



}
public static final String SMS_RECEIVED =
    "android.provider.Telephony.SMS_RECEIVED";
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   IntentFilter inf = new IntentFilter(SMS_RECEIVED);
    SmsReceiver sr = new SmsReceiver();
    registerReceiver(sr, inf);

}

}

我已正确授予权限。 但是当我试图在Manifest中注册broadcastreceiver时 它强制关闭应用程序, 我不知道如何给日志,如果有人请告诉我。

答案 1 :(得分:0)

你还记得给它适当的许可吗?

我相信你的清单中的短信,你必须有类似的东西:

android.permission.RECEIVE_SMS