【问题标题】:How to extract data from a received sms and use it in another activity?如何从收到的短信中提取数据并将其用于另一个活动?
【发布时间】:2011-10-30 23:30:04
【问题描述】:

我有一个应用程序需要从收到的消息中获取数据,然后将此数据传递给另一个活动以供其他用途。我已经从收到的短信中提取了数据,但是如何从当前的 java 文件中传递它以使用它在其他java文件中吗?

public class ReceivelocationActivity extends BroadcastReceiver   {

private LocationManager hdLocMgr;
private String hdLocProvider;

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    Intent m=new Intent(context, ReceivelocationActivity.class);    
      PendingIntent pi=PendingIntent.getBroadcast(context, 0, m, 0); 
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    String str = ""; 
    String str2="";
    String str3="";
    String autoReplyToken = "Request_Accepted";
    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();
         str3=msgs[i].getMessageBody().toString();
            str += "\n";        
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
      //  int number=Integer.parseInt(str2);

     // retrieve th current location
        Criteria hdCrit = new Criteria();
        hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
        hdCrit.setAltitudeRequired(false);
        hdCrit.setBearingRequired(false);
        hdCrit.setCostAllowed(true);
        hdCrit.setPowerRequirement(Criteria.POWER_LOW);

        hdLocMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        hdLocProvider = hdLocMgr.getBestProvider(hdCrit, true); 

        Location location = hdLocMgr.getLastKnownLocation(hdLocProvider);

        Double dlat = location.getLatitude();
        Double dlon = location.getLongitude();


        String mymsg = Double.toString(dlat) + " " +Double.toString(dlon) ; 

        boolean isAutoReply = str3.startsWith(autoReplyToken);

        if (!isAutoReply) {
            SmsManager sms = SmsManager.getDefault();
            String autoReplyText = autoReplyToken + " "+mymsg;
            sms.sendTextMessage(str2, null, autoReplyText, pi, null);
        }

      /* Part as suggested by you to pass a string to friendlocation.class  */  
        Intent in = new Intent(context, Friendlocation.class);
        in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        in.putExtra("latlongstring", str3);
        context.startActivity(in);
    }                 
}



    public class Friendlocation extends MapActivity implements LocationListener {
     /** Called when the activity is first created. */
private static final String TAG = "LocationActivity";
LocationManager locationManager; 
  Geocoder geocoder; 
  TextView locationText;
  MapView map;  
  MapController mapController; 
  GeoPoint point;

  class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long   when) 
        {
            super.draw(canvas, mapView, shadow);                   

            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(point, screenPts);

            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.androidmarker);            
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
            return true;
        }
    } 


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main4);



    locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
    map = (MapView)this.findViewById(R.id.mapview);
    map.setBuiltInZoomControls(true);

    mapController = map.getController(); 
    mapController.setZoom(16);


    String latlon = getIntent().getStringExtra("latlongstring");
    this.friendlocation(latlon);

}



public void friendlocation(String latlon) { 

    String [] location = latlon.split("\\s+");
    double alt=0;
    double bear=0;
    double lat= Double.valueOf(location[0].trim()).doubleValue();
    double lon=Double.valueOf(location[1].trim()).doubleValue();

  String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", lat, 
                lon, alt,bear);
  this.locationText.setText(text);

  try {
    List<Address> addresses = geocoder.getFromLocation(lat, lon,10); //<10>
    for (Address address : addresses) {
      this.locationText.append("\n" + address.getAddressLine(0));
    }

    int latitude = (int)(lat * 1000000);
    int longitude = (int)(lon * 1000000);

    point = new GeoPoint(latitude,longitude);


   mapController.animateTo(point);   
   MapOverlay mapOverlay = new MapOverlay();
   List<Overlay> listOfOverlays = map.getOverlays();
   listOfOverlays.clear();
   listOfOverlays.add(mapOverlay);


    map.invalidate();

  } catch (IOException e) {
    Log.e("LocateMe", "Could not get friend location", e);
  }
}

整个日志猫错误:

10-31 23:07:34.884: D/ddm-heap(234): 收到功能列表请求 10-31 23:08:05.443: E/ActivityThread(234): 找不到 com.google.settings 的提供者信息 10-31 23:08:05.443: E/ActivityThread(234): 找不到 com.google.settings 的提供者信息 10-31 23:08:05.475: E/ActivityThread(234): 找不到 com.google.settings 的提供者信息 10-31 23:08:05.593: D/LocationManager(234): 构造函数: service = android.location.ILocationManager$Stub$Proxy@44dd4c38 10-31 23:08:05.772:I/MapActivity(234):处理网络更改通知:已连接 10-31 23:08:05.772: E/MapActivity(234): 无法获取连接工厂客户端 10-31 23:08:12.012: D/LocationManager(234): removeUpdates: listener = com.example.gui.SendlocationActivity@44db4af0 10-31 23:08:12.112: E/ActivityThread(234): 找不到 com.google.settings 的提供者信息 10-31 23:08:12.112: E/ActivityThread(234): 找不到 com.google.settings 的提供者信息 10-31 23:08:12.122: W/MapActivity(234): 回收调度程序 com.google.googlenav.datarequest.DataRequestDispatcher@44db89f0 10-31 23:08:12.142: V/MapActivity(234): 回收地图对象。 10-31 23:08:13.472: D/AndroidRuntime(234): 关闭虚拟机 10-31 23:08:13.472: W/dalvikvm(234): threadid=3: 线程退出未捕获异常 (group=0x4001b188) 10-31 23:08:13.482:E/AndroidRuntime(234):未捕获的处理程序:线程主因未捕获的异常而退出 10-31 23:08:13.822: E/AndroidRuntime(234): java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.gui/com.example.gui.Friendlocation}: java.lang.NullPointerException 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.ActivityThread.access$2200(ActivityThread.java:119) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.os.Handler.dispatchMessage(Handler.java:99) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.os.Looper.loop(Looper.java:123) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.ActivityThread.main(ActivityThread.java:4363) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 java.lang.reflect.Method.invokeNative(Native Method) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 java.lang.reflect.Method.invoke(Method.java:521) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 10-31 23:08:13.822: E/AndroidRuntime(234): at dalvik.system.NativeStart.main(Native Method) 10-31 23:08:13.822:E/AndroidRuntime(234):由:java.lang.NullPointerException 引起 10-31 23:08:13.822: E/AndroidRuntime(234): 在 com.example.gui.Friendlocation.friendlocation(Friendlocation.java:110) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 com.example.gui.Friendlocation.onCreate(Friendlocation.java:89) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-31 23:08:13.822: E/AndroidRuntime(234): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 10-31 23:08:13.822: E/AndroidRuntime(234): ... 11 更多 10-31 23:08:13.842: I/dalvikvm(234): threadid=7: 对信号 3 做出反应 10-31 23:08:13.972: I/dalvikvm(234): 将堆栈跟踪写入“/data/anr/traces.txt” 10-31 23:08:21.046: I/Process(234): 发送信号。 PID:234 SIG:9 10-31 23:08:21.574: E/ActivityThread(253): 找不到 com.google.settings 的提供者信息 10-31 23:08:21.574: E/ActivityThread(253): 找不到 com.google.settings 的提供者信息 10-31 23:08:21.593: E/ActivityThread(253): 找不到 com.google.settings 的提供者信息 10-31 23:08:21.733: D/LocationManager(253): 构造函数: service = android.location.ILocationManager$Stub$Proxy@44dcb680 10-31 23:08:21.753: D/LocationActivity(253): Location[mProvider=gps,mTime=1319979600000,mLatitude=10.0,mLongitude=10.0,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0, mHasBearing=false,mBearing=0.0,mHasAccuracy=false,mAccuracy=0.0,mExtras=null] 10-31 23:08:21.863:I/MapActivity(253):处理网络更改通知:已连接 10-31 23:08:21.863: E/MapActivity(253): 无法获取连接工厂客户端

【问题讨论】:

  • 您能否发布应用程序崩溃时在 Logcat 中打印出的异常的完整堆栈跟踪?有很多事情可能会出错,但堆栈跟踪会告诉我们 Android 到底在哪里崩溃。
  • @plowman :我已经粘贴了整个日志 cat.sorry for the bad presentation,但我认为完全复制它会使它更清楚。如果您有什么想问的,请随时询问并提前致谢。
  • 根据堆栈跟踪,问题出在at com.example.gui.Friendlocation.friendlocation(Friendlocation.java:110) 所以在Friendlocation.java 内部,在friendlocation() 方法内部,在line 110 上,你正试图调用一个方法无效的。我怀疑它与String[] location 有关,因此您应该在调用location[0]location[1] 之前检查location.length == 2。您还应该在尝试使用它们之前打印出latlonlocation,这样您就可以确定它们是您所期望的。
  • @plowman : 但是如何打印这些值,我的意思是我不能像以前在 java 中那样在控制台上打印它们。请问如何检查纬度和位置?跨度>
  • 你试过System.out.println()吗?

标签: android sms


【解决方案1】:

您可以使用 Intent 在活动之间传递数据。在您接收 SMS 的 BroadcastReceiver 中,您可以执行以下操作:

@Override
public void onReceive(Context context, Intent intent) {
    byte[] pdu = new byte[0]; //obviously use the real pdu in your app
    Intent intent = new Intent(this, NewActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("smsPdu", pdu);
    context.startActivity(intent);
}

然后,在 NewActivity 内部,您可以执行以下操作:

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
        SmsMessage message = SmsMessage.createFromPdu(pdu);
}

请参阅文档 here 以更全面地了解 Intent。

【讨论】:

  • @ plowman:在编写 StartActivity(intent) 时出现错误,显示“创建方法 startActivity()”。我的接收类扩展了 BroadcastReceiver。你能告诉我为什么会这样吗?
  • @code_hacker :我已经编辑了我的示例以使其更加清晰。您可以使用 Context 的任何实例以及从 Activity 的任何方法中调用 startActivity()。请注意我添加 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 的部分 - 这对于避免崩溃很重要。如果这仍然没有意义,请告诉我。
  • 我完全按照你说的做了,但是收到短信时我的应用程序崩溃了。我正在放置两个文件(receivesms.java 和friendlocation.java)。请看一下,让我知道这可能是什么原因吗?
猜你喜欢
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2014-03-02
  • 2015-12-31
相关资源
最近更新 更多