我希望有一个短信接收处理程序,当收到短信时会做一些事情,我是新手,所以我不知道我在做什么,我尝试了一些东西,但它没有用。当我通过telnet将短信发送到模拟器时,处理程序不会被执行
这是我的代码:
package com.example.kk;
public class MainActivity extends MapActivity {
MapView mapView;
MapController mc;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SmsReceiver smsreceiver = new SmsReceiver();
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
@SuppressWarnings("deprecation")
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mc = mapView.getController();
Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// ---retrieve the SMS message 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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
// ---display the new SMS message---
}
}
}
}
答案 0 :(得分:0)
您需要将此添加到该接收器中的清单
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
答案 1 :(得分:0)
你应该有RECEIVE_SMS权限和注册接收者来获取短信事件。你有RECEIVE_SMS权限吗?我看不到你注册收件人的任何地方。
您可以通过清单或代码注册接收者。我看到你创建了接收器(SmsReceiver smsreceiver = new SmsReceiver();)但你没有注册它。 Check this post