我想开发一个短信通知器。问题是当收到短信时,活动中的文本框只需更改为“收到短信”文本。SMS 发送成功,但 BroadCastReceiver 无法正常工作,请帮助。
我的代码:
package com.shahid.todolist;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* SmsManager smsManager = SmsManager.getDefault();
*
* String sendTo = "03129912287"; String myMessage =
* "Android supports programmatic SMS messaging!";
* smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
*/
final EditText phoneNo = (EditText) findViewById(R.id.phoneNo);
final TextView display = (TextView) findViewById(R.id.txtDisplay);
Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
SmsManager smsManager = SmsManager.getDefault();
display.setText("Sending SMS...");
String sendTo = phoneNo.getText().toString();
String myMessage = "This is Shahid from Android";
smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
}
});
// ---
final BroadcastReceiver receiver = new BroadcastReceiver() {
private static final String queryString = "@echo ";
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent _intent) {
if (_intent.getAction().equals(SMS_RECEIVED)) {
display.setText("SMS Received");
}
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}