我是 android 的新手,我试图在收到新消息时获取短信的编号,我为此使用广播接收器。但是当收到一条新消息时,我的“广播接收器”课程无法正常工作。谁能帮我找出问题所在。在下面给出我的代码..
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
}
public class MyBroadcastReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String smsnumber = "";
if (bundle != null)
{
//---retrieve the sender number SMS received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
smsnumber = msgs[i].getOriginatingAddress();
}
}
}
}
}
我已经在清单中给出了接收标签。
<receiver android:name="com.aucupa.iack.MyBroadcastReciever" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
也获得了接收短信的使用权限..
<uses-permission android:name="android.permission.RECEIVE_SMS" />
但是当一条短信没有来自 MyBroadcastReciever 类的响应时。当我调试控件时,MyBroadcastReciever 类没有响应。请帮我找出问题所在
最后我从你的帮助中得到了答案,在这里给出我的答案..
public class MainActivity extends Activity
{
MyBroadcastReciever broadcastreciever = new MyBroadcastReciever();
static final String SOME_ACTION = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
Intent i = new Intent(SOME_ACTION);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
sendBroadcast(i);
context.registerReceiver(broadcastreciever, intentFilter);
}
public class MyBroadcastReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction() == "android.provider.Telephony.SMS_RECEIVED"){
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String smsnumber = "";
if (bundle != null)
{
//---retrieve the sender number SMS received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
smsnumber = msgs[i].getOriginatingAddress();
}
}
}
}
}
}