0

我想要一个 SMS 接收器处理程序,它会在收到 SMS 时执行某些操作,我是 android 新手,所以我不知道我到底在做什么,我尝试了一些东西,但它不起作用。当我通过 telnet 向模拟器发送短信时,处理程序没有被执行

这是我的代码:

包 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---
        }
    }
}

}
4

2 回答 2

0

您需要将此添加到该接收器的清单中

<intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
于 2013-01-17T20:06:26.183 回答
0

您应该拥有 RECEIVE_SMS 权限并注册接收方以获取短信事件。你有RECEIVE_SMS 权限吗?我看不到您注册接收者的任何地方。

您可以通过清单或代码注册接收者。我看到你创建了接收者 (SmsReceiver smsreceiver = new SmsReceiver();) 但你没有注册它。检查这篇文章

于 2013-01-17T20:21:30.910 回答