使用从一个类到另一个类的变量

时间:2013-04-24 15:28:42

标签: android android-intent

我想在ReveiveSMS.class的主类中使用vaiable。 这是我的ReceiveSMS.class代码,我想在main中使用messageBody。 帮帮我怎么办呢。谢谢

package com.formation.gmaps;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class ReceiveSMS  extends BroadcastReceiver
{
 private final String   ACTION_RECEIVE_SMS  = "android.provider.Telephony.SMS_RECEIVED";

 @Override
 public void onReceive(Context context, Intent intent)
 {
 if (intent.getAction().equals(ACTION_RECEIVE_SMS))
 {
 Bundle bundle = intent.getExtras();
 if (bundle != null)
 {
 Object[] pdus = (Object[]) bundle.get("pdus");

 final SmsMessage[] messages = new SmsMessage[pdus.length];
 for (int i = 0; i < pdus.length; i++)  {  messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);  }  if (messages.length > -1)
 {
 final String messageBody = messages[0].getMessageBody();
 final String phoneNumber = messages[0].getDisplayOriginatingAddress();

 Toast.makeText(context, "Expediteur : " + phoneNumber, Toast.LENGTH_LONG).show();
 Toast.makeText(context, "Message : " + messageBody, Toast.LENGTH_LONG).show();



 }
 }
 }

 }

}

1 个答案:

答案 0 :(得分:0)

您可以将messageBody放入SharedPreferences

在ReceiveSMS课程中:

SharedPreferences prefs = getSharedPreferences("yourPrefs", 0);

SharedPreferences.Editor editor = prefs.edit();
editor.putString("messageBody", messageBody);
editor.commit();

在你的主要课程中:

SharedPreferences prefs = getSharedPreferences("yourPrefs", 0);
String messageBody = prefs.getString("messageBody","defaultValue");