1

我正在开发始终在后台运行并自动响应 SMS 字符串而无需用户交互的 android 手机监控应用程序我成功获得了活动中的电池电量和 GPS 坐标,但无法将这些值从活动传递到广播接收器,然后自动发送这些值作为对 SMS 字符串的回复。

这是将值从活动类传递到广播接收器类的代码:

String info = "Battery Level: " + level + "%\n";
            setBatteryLevelText(info);

            Intent in = new Intent("my.action.string");
            in.putExtra("stat", info);
            startActivity(in);
            sendBroadcast(in);

广播接收器类中的代码:

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
String batt = getIntent().getStringExtra("stat");
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();                    
      str2=msgs[i].getOriginatingAddress();
      str += " :";
      str += msgs[i].getMessageBody().toString();
      str += "\n";      

    //---display the new SMS message---
      Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    //  int number=Integer.parseInt(str2);
      SmsManager sms = SmsManager.getDefault();

      String autoReplybat = "Battery";
      boolean isAutoReplybat = msgs[i].getMessageBody().toString().equals(autoReplybat);
      if (!isAutoReplybat) {

          sms.sendTextMessage(str2, null,  batt, pi, null);
          }

GPS 坐标(数据类型为 double)也有同样的问题,我无法自动回复 GPS 坐标和电池电量。从我这边来看,空消息会根据 SMS 字符串自动发送。我想问题是将值从活动传递到广播接收器请帮助我并纠正我的逻辑/语法错误提前谢谢

4

3 回答 3

0

尝试这个

 String batt = intent.getStringExtra("stat")
于 2013-03-06T15:20:30.463 回答
0

当您应该使用传递给 onReceive 函数的意图变量时,您正在调用 getIntent() 来检索额外内容。

编辑:

在接收器的顶部,您有:

   @Override
   public void onReceive(Context context, Intent intent) {
       // TODO Auto-generated method stub
          String batt = getIntent().getStringExtra("stat");

将其更改为:

   @Override
   public void onReceive(Context context, Intent intent) {
       // TODO Auto-generated method stub
          String batt = intent.getStringExtra("stat");
于 2013-03-06T15:20:46.937 回答
0
Intent intent = new Intent("my.action.string"); 
intent.putExtra("phonenum", "98588685959"); 
sendBroadcast(intent);

public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  Log.i("Receiver", "Broadcast received: " + action);
  if(action.equals("my.action.string")){
     String state = intent.getExtras().getString("phonenum");
 }
}
于 2020-06-25T18:20:04.163 回答