为什么';my ReceiveMessage.java类是否将SMS正文设置为my textview?
我在活动中有一个按钮。通过点击它,一条带有预定义正文和电话地址的短信被发送,然后一条包含代码的回复短信被自动发送到我的手机。我需要接收代码并将其设置为我的文本视图。我怎样才能解决它?我有两个活动:MainActivity和MessageReceiver为什么';my ReceiveMessage.java类是否将SMS正文设置为my textview?,java,android,textview,sms,Java,Android,Textview,Sms,我在活动中有一个按钮。通过点击它,一条带有预定义正文和电话地址的短信被发送,然后一条包含代码的回复短信被自动发送到我的手机。我需要接收代码并将其设置为我的文本视图。我怎样才能解决它?我有两个活动:MainActivity和MessageReceiver //MessageReceiver.java public class MessageReceiver extends BroadcastReceiver { public void onReceive(Conte
//MessageReceiver.java
public class MessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] messages;
String str = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
messages = new SmsMessage[pdus != null ? pdus.length : 0];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) (pdus != null ? pdus[i] : null));
str += messages[i].getOriginatingAddress();
str += ":";
str += messages[i].getMessageBody();
str += "\n";
}
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECIEVED_ACTION");
broadcastIntent.putExtra("message", str);
context.sendBroadcast(broadcastIntent);}}}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dearzeinab.emaapplication">
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.dearzeinab.emaapplication.MessageReceiver" android:enabled="true">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
您需要注册您的接收器 像这样:
getActivity().registerReceiver(intentReceiver, new IntentFilter("SMS_RECIEVED_ACTION"));
只有到那时它才会起作用
下面是它在代码中的外观:
//MainActivity.java
private BroadcastReceiver intentReceiver; // do not set it up here. We'll set it and register it onCreate(), but we'll keep it here so it stays on scope of every other function
private IntentFilter intentFilter; // same for the filter
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// We'll set up the receiver here, after the activity starts
intentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TextView chargeText = (TextView) findViewById(R.id.chargeText);
Log.d("myTag", "is chargeText null? : " + (chargeText==null));
Log.d("myTag", "The text is: " + (intent.getExtras().getString("message")));
String text = intent.getExtras().getString("message").toString(); // let's try this with toString() so we are very explicit about it
Log.d("myTag", "The converted text is: " + text);
chargeText.setText(text);
}
};
// then, we'll create the filter
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
button3 = (Button) findViewById(R.id.button);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String mymsg = "CMDACC_1234";
String thenumber = "09380638202";
SendChargeMessage(thenumber, mymsg);
}
});
registerReceiver(intentReceiver , intentFilter); // registering
}
public void SendChargeMessage(String thenumber, String mymsg) {
String SENT = "Message sent";
String DELIVERED = "Message delivered";
SmsManager smsManager = SmsManager.getDefault();
Context curContext = this.getApplicationContext();
PendingIntent sentPending = PendingIntent.getBroadcast(curContext, // Are you sure you want to create a new intent here?
0, new Intent("SENT"), 0);
curContext.registerReceiver(new BroadcastReceiver() { // and are you sure this is supposed to be a new receiver as well? Are you registering it like we did with iontentReceiver?
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Sent.",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Not Sent: Generic failure.",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "Not Sent: No service (possibly, no SIM-card).",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Not Sent: Null PDU.",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Not Sent: Radio off (possibly, Airplane mode enabled in Settings).",
Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter("SENT"));
PendingIntent deliveredPending = PendingIntent.getBroadcast(curContext,
0, new Intent("DELIVERED"), 0);
curContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Delivered.",
Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "Not Delivered: Canceled.",
Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter("DELIVERED"));
PackageManager pm = this.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
Toast.makeText(this, "Sorry, your device probably can't send SMS...", Toast.LENGTH_SHORT).show();
} else {
smsManager.sendTextMessage("09380638202", null, "CMDACC_1234", sentPending, deliveredPending);
//chargeText.setText(SMSBody1);
}
}
我在你的代码中看到:
//MainActivity.java
private BroadcastReceiver intentReceiver; // do not set it up here. We'll set it and register it onCreate(), but we'll keep it here so it stays on scope of every other function
private IntentFilter intentFilter; // same for the filter
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// We'll set up the receiver here, after the activity starts
intentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TextView chargeText = (TextView) findViewById(R.id.chargeText);
Log.d("myTag", "is chargeText null? : " + (chargeText==null));
Log.d("myTag", "The text is: " + (intent.getExtras().getString("message")));
String text = intent.getExtras().getString("message").toString(); // let's try this with toString() so we are very explicit about it
Log.d("myTag", "The converted text is: " + text);
chargeText.setText(text);
}
};
// then, we'll create the filter
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
button3 = (Button) findViewById(R.id.button);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String mymsg = "CMDACC_1234";
String thenumber = "09380638202";
SendChargeMessage(thenumber, mymsg);
}
});
registerReceiver(intentReceiver , intentFilter); // registering
}
public void SendChargeMessage(String thenumber, String mymsg) {
String SENT = "Message sent";
String DELIVERED = "Message delivered";
SmsManager smsManager = SmsManager.getDefault();
Context curContext = this.getApplicationContext();
PendingIntent sentPending = PendingIntent.getBroadcast(curContext, // Are you sure you want to create a new intent here?
0, new Intent("SENT"), 0);
curContext.registerReceiver(new BroadcastReceiver() { // and are you sure this is supposed to be a new receiver as well? Are you registering it like we did with iontentReceiver?
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Sent.",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Not Sent: Generic failure.",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "Not Sent: No service (possibly, no SIM-card).",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Not Sent: Null PDU.",
Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Not Sent: Radio off (possibly, Airplane mode enabled in Settings).",
Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter("SENT"));
PendingIntent deliveredPending = PendingIntent.getBroadcast(curContext,
0, new Intent("DELIVERED"), 0);
curContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Delivered.",
Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "Not Delivered: Canceled.",
Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter("DELIVERED"));
PackageManager pm = this.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
Toast.makeText(this, "Sorry, your device probably can't send SMS...", Toast.LENGTH_SHORT).show();
} else {
smsManager.sendTextMessage("09380638202", null, "CMDACC_1234", sentPending, deliveredPending);
//chargeText.setText(SMSBody1);
}
}
- 您在onStart()之前注册了一个接收器。该接收器适用于每种方法。但它没有注册
- 您正在onResume()中创建一个新的接收器,其名称与前一个(broadcastReceiver)相同。您正确地注册了这个函数,但它超出了每个函数的范围
- 这意味着您试图访问一个未注册的接收者,并且您正在注册一个同名但超出范围的接收者
- 研究范围及其在面向对象编程中的工作方式
- 研究接受者、意图以及如何注册它们
祝你好运,朋友。在你的接收器中使用下面的代码
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (Object aPdusObj : pdusObj) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String senderAddress = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.d(TAG, "Received SMS: " + message + ", Sender: " + senderAddress);
// if the SMS is not from our gateway, ignore the message
if (!senderAddress.toLowerCase().contains(GlobalApplication.SMS_ORIGIN.toLowerCase())) {
return;
}
// verification code from sms
String verificationCode = getVerificationCode(message);
Log.d(TAG, "OTP received: " + verificationCode);
mListener.otpReceived(verificationCode);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
/**
* Getting the OTP from sms message body
* ':' is the separator of OTP from the message
*
* @param message
* @return
*/
private String getVerificationCode(String message) {
String str_msg = message.replace("Dear Customer,","");
str_msg = str_msg.replace("is your one time password (OTP). Please enter the OTP to proceed.","");
str_msg = str_msg.replace("Thank you,","");
str_msg = str_msg.replace("ChannelPaisa","");
str_msg = str_msg.replace("\n","");
str_msg= str_msg.trim().toString();
return str_msg;
}
谢谢不,没用。我收到短信,短信正文显示为祝酒词,但它没有在文本视图中设置。哦,我的糟糕。我以为你的问题是接收消息,而不是在文本视图上设置它。收到消息时,请检查空值和文本本身。我会更新我的帖子,让你看看如何更新。谢谢你的回答。但问题尚未解决。我编辑了我的问题并添加了我使用的全部代码。请看一下。看了你的代码后,我想你在注册接收者后定义了intentFilter。因此,接收器正在向空intentFilter注册。请你试着把它们按正确的顺序排列好吗?只是为了验证这个想法。能否尝试将所有内容(创建intentFilter、创建和注册接收者)都放在onResume()中?谢谢。你的意思是我应该像onResume()中编辑过的代码那样做吗?