How to extract data from a received sms and use it in another activity?

ぃ、小莉子 提交于 2019-12-23 05:59:09

问题


I have an application which requires data to be fetched from a received message and then pass this data to another activity for other uses.I have extracted the data from a received sms but how can I pass this from current java file to use it in other java file ?

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);
  }
}

the entire log cat error :

10-31 23:07:34.884: D/ddm-heap(234): Got feature list request 10-31 23:08:05.443: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:05.443: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:05.475: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:05.593: D/LocationManager(234): Constructor: service = android.location.ILocationManager$Stub$Proxy@44dd4c38 10-31 23:08:05.772: I/MapActivity(234): Handling network change notification:CONNECTED 10-31 23:08:05.772: E/MapActivity(234): Couldn't get connection factory client 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): Failed to find provider info for com.google.settings 10-31 23:08:12.112: E/ActivityThread(234): Failed to find provider info for com.google.settings 10-31 23:08:12.122: W/MapActivity(234): Recycling dispatcher com.google.googlenav.datarequest.DataRequestDispatcher@44db89f0 10-31 23:08:12.142: V/MapActivity(234): Recycling map object. 10-31 23:08:13.472: D/AndroidRuntime(234): Shutting down VM 10-31 23:08:13.472: W/dalvikvm(234): threadid=3: thread exiting with uncaught exception (group=0x4001b188) 10-31 23:08:13.482: E/AndroidRuntime(234): Uncaught handler: thread main exiting due to uncaught exception 10-31 23:08:13.822: E/AndroidRuntime(234): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gui/com.example.gui.Friendlocation}: java.lang.NullPointerException 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.os.Handler.dispatchMessage(Handler.java:99) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.os.Looper.loop(Looper.java:123) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.main(ActivityThread.java:4363) 10-31 23:08:13.822: E/AndroidRuntime(234): at java.lang.reflect.Method.invokeNative(Native Method) 10-31 23:08:13.822: E/AndroidRuntime(234): at java.lang.reflect.Method.invoke(Method.java:521) 10-31 23:08:13.822: E/AndroidRuntime(234): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 10-31 23:08:13.822: E/AndroidRuntime(234): at 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): Caused by: java.lang.NullPointerException 10-31 23:08:13.822: E/AndroidRuntime(234): at com.example.gui.Friendlocation.friendlocation(Friendlocation.java:110) 10-31 23:08:13.822: E/AndroidRuntime(234): at com.example.gui.Friendlocation.onCreate(Friendlocation.java:89) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-31 23:08:13.822: E/AndroidRuntime(234): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 10-31 23:08:13.822: E/AndroidRuntime(234): ... 11 more 10-31 23:08:13.842: I/dalvikvm(234): threadid=7: reacting to signal 3 10-31 23:08:13.972: I/dalvikvm(234): Wrote stack trace to '/data/anr/traces.txt' 10-31 23:08:21.046: I/Process(234): Sending signal. PID: 234 SIG: 9 10-31 23:08:21.574: E/ActivityThread(253): Failed to find provider info for com.google.settings 10-31 23:08:21.574: E/ActivityThread(253): Failed to find provider info for com.google.settings 10-31 23:08:21.593: E/ActivityThread(253): Failed to find provider info for com.google.settings 10-31 23:08:21.733: D/LocationManager(253): Constructor: 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): Handling network change notification:CONNECTED 10-31 23:08:21.863: E/MapActivity(253): Couldn't get connection factory client


回答1:


You can pass data between activities using Intents. In the BroadcastReceiver where you receive the SMS, you can do something like this:

@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);
}

Then, inside of NewActivity, you can do something like this:

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

See the documentation here for a more thorough overview of Intents.



来源:https://stackoverflow.com/questions/7948676/how-to-extract-data-from-a-received-sms-and-use-it-in-another-activity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!