我正在制作一个应用程序,用于通过 SMS 进行轮询。我想要的是,如果有人说“是”,我的“是”计数会得到 +1,“否”的情况也是如此,我希望在后台完成,所以我正在使用服务。并在我的MainActivity
. 我尝试了,并制作了以下代码:: BroadcastReciver
/*Bundle bundle = intent.getExtras();
SmsMessage[] msg = null;
String body = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msg = new SmsMessage[pdus.length];
for (int i = 0; i < msg.length; i++) {
body = msg[i].getMessageBody().toString();
}
}*/
String body = "yes";
if(body.equals("YES") || body.equals("yes")|| body.equals("y") || body.equals("Y")){
Intent yes = new Intent(context,PollCounter.class);
yes.putExtra("yes", true);
yes.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(yes);
context.stopService(yes);
}
else if(body.equals("NO") || body.equals("no")|| body.equals("n") || body.equals("N")){
Intent no = new Intent(context,PollCounter.class);
no.putExtra("no", true);
no.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(no);
context.stopService(no);
}
else {
Intent invalidMsg = new Intent(context,PollCounter.class);
invalidMsg.putExtra("invalidMsg", true);
context.startService(invalidMsg);
}
}
}
BroadcastReceiver 也有问题,当我取消注释下列的
/*Bundle bundle = intent.getExtras();
SmsMessage[] msg = null;
String body = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msg = new SmsMessage[pdus.length];
for (int i = 0; i < msg.length; i++) {
body = msg[i].getMessageBody().toString();
}
}*/
不明白原因,我之前使用过这段代码并且它正在工作。
在Service
::
boolean yes = intent.getBooleanExtra("yes", false);
boolean no = intent.getBooleanExtra("no", false);
boolean invalidMsg = intent.getBooleanExtra("invalidMsg", false);
if (yes) {
yesCount++;
Intent intentYes = new Intent(this,MainActivity.class);
intentYes.putExtra("yesCount", yesCount);
startActivity(intentYes);
Toast.makeText(getBaseContext(), "yes is recvd", Toast.LENGTH_LONG).show();
} else if (no) {
noCount++;
Intent intentNo = new Intent(this,MainActivity.class);
intentNo.putExtra("yesCount", noCount);
startActivity(intentNo);
Toast.makeText(getBaseContext(), "no is recvd", Toast.LENGTH_LONG).show();
} else {
invalidMsgCount++;
Intent intentInavalidMsg = new Intent(this,MainActivity.class);
intentInavalidMsg.putExtra("yesCount", invalidMsgCount);
Toast.makeText(getBaseContext(), "Invalid is recvd", Toast.LENGTH_LONG).show();
}
}
我尝试使用Bundle b = intent.getExtras();
但我不确定如何使用它,以及我应该使用什么进行初始化intent
。
谢谢...
PS:我是安卓新手。对不起,如果我的问题有点奇怪或者我的编码看起来很奇怪。