Android 如何从收到的短信中提取数据并将其用于其他活动?

Android 如何从收到的短信中提取数据并将其用于其他活动?,android,sms,Android,Sms,我有一个应用程序,它要求从接收到的消息中提取数据,然后将此数据传递给另一个活动以供其他用途。我已从接收到的sms中提取了数据,但如何从当前java文件传递此数据以在其他java文件中使用 public class ReceivelocationActivity extends BroadcastReceiver { private LocationManager hdLocMgr; private String hdLocProvider; @Override public void o

我有一个应用程序,它要求从接收到的消息中提取数据,然后将此数据传递给另一个活动以供其他用途。我已从接收到的sms中提取了数据,但如何从当前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);
  }
}
公共类ReceivelocationActivity扩展了BroadcastReceiver{
私人位置经理hdLocMgr;
私有字符串提供程序;
@凌驾
公共void onReceive(上下文、意图){
//TODO自动生成的方法存根
意图m=新意图(上下文,ReceivelocationActivity.class);
PendingIntent pi=PendingIntent.getBroadcast(上下文,0,m,0);
Bundle=intent.getExtras();
SmsMessage[]msgs=null;
字符串str=“”;
字符串str2=“”;
字符串str3=“”;
字符串autoReplyToken=“已接受请求”;
if(bundle!=null)
{
//---检索收到的SMS消息---
Object[]pdus=(Object[])bundle.get(“pdus”);
msgs=新SMS消息[PDU.length];

对于(int i=0;i您可以使用意图在活动之间传递数据。在接收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);
}
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
        SmsMessage message = SmsMessage.createFromPdu(pdu);
}
然后,在NewActivity中,您可以执行以下操作:

@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);
}
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
        SmsMessage message = SmsMessage.createFromPdu(pdu);
}

有关意向的更全面概述,请参阅文档。

您可以使用意向在活动之间传递数据。在接收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);
}
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
        SmsMessage message = SmsMessage.createFromPdu(pdu);
}
然后,在NewActivity中,您可以执行以下操作:

@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);
}
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        byte[] pdu = getIntent().getByteArrayExtra("smsPdu");
        SmsMessage message = SmsMessage.createFromPdu(pdu);
}

请参阅文档以了解更全面的意图概述。

@plowman:在编写StartActivity(意图)时,我在显示“create method StartActivity()”时出错。我的receivingsms类扩展了BroadcastReceiver。你能告诉我为什么会这样吗?@code\u hacker:我编辑了我的示例以便更清楚。你可以调用StartActivity()使用上下文的任何实例以及活动的任何方法。请注意我添加
intent.setFlags(intent.FLAG\u Activity\u NEW\u TASK)的部分
-这对于避免崩溃很重要。如果这仍然没有意义,请告诉我。我完全按照你说的做了,但是收到短信时我的应用程序崩溃。我正在放置两个文件(receivesms.java和friendlocation.java)。请看一看,让我知道可能的原因是什么?@plowman:在编写StartActivity(intent)时,我收到一个错误,显示“create method StartActivity()”.My receivingsms类扩展了BroadcastReceiver。你能告诉我为什么会这样吗?@code\u hacker:我已经编辑了我的示例以便更清楚。你可以使用上下文的任何实例以及活动的任何方法调用startActivity()。请注意我添加
intent.setFlags(intent.FLAG\u Activity\u NEW\u TASK)的部分
-这对于避免崩溃很重要。如果这仍然没有意义,请告诉我。我完全按照你说的做了,但是收到短信时我的应用程序崩溃。我正在放置两个文件(receivesms.java和friendlocation.java)。请看一看,让我知道可能的原因是什么?你能发布应用程序崩溃时在Logcat中打印出的异常的完整堆栈跟踪吗?有很多事情可能会出错,但堆栈跟踪会告诉我们Android崩溃的确切位置。@plowman:我已经粘贴了整个Logcat。很抱歉他说这个演示很糟糕,但我认为准确地复制它会让它更清楚。如果有什么你想问的,请随时提问并提前感谢。根据堆栈跟踪,问题是com.example.gui.Friendlocation.Friendlocation(Friendlocation.java:110)上的
因此在
Friendlocation.java
中,在
Friendlocation()方法中,在
第110行
上,您试图对空值的对象调用方法。我怀疑它与
字符串[]位置
相关,因此在调用
位置[0]之前,您应该检查
位置.length==2
位置[1]
。在尝试使用它们之前,您还应该打印出
latlon
location
,这样您就可以确保它们是您所期望的。@plowman:但是如何打印这些值,我的意思是我不能像在java中那样在控制台上打印它们。请问您可以如何检查latlon和location吗?您是否尝试过
System.out.println()
?当你的应用程序崩溃时,你能发布在Logcat中打印出的异常的完整堆栈跟踪吗?有很多事情可能会出错,但堆栈跟踪会告诉我们Android崩溃的确切位置。@plowman:我已经粘贴了完整的日志跟踪。很抱歉,演示不好,但我认为准确地复制它会使它更clear.如果你想问什么,请随时提问并提前表示感谢。根据堆栈跟踪,问题是com.example.gui.Friendlocation.Friendlocation(Friendlocation.java:110)
中的
Friendlocation.java
,在
Friendlocation()中
method,在
第110行
上,您试图调用一个空值的方法。我怀疑它与
String[]location
有关,所以在调用
location[0]
location[1]之前,您应该检查
location.length==2
。在尝试使用它们之前,您还应该打印出
latlon
location
,这样您就可以确保它们是您所期望的。@plowman:但是如何打印这些值,我的意思是我不能像在java中那样在控制台上打印它们。请问您可以如何检查latlon和location吗?您是否尝试过
System.out.println()