我有两个类,其中一个扩展活动,另一个扩展 BroadcastReceiver 。我已在 MainActivity 类中声明了一些变量并且需要在 IncomingSms 类中使用它。我如何使用变量。这是我的代码。
在MainActivity类中,我需要在IncomingSms类中使用变量full_address。 的 MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy stricMode = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stricMode);
}
TextView address_textview =(TextView)findViewById(R.id.address);
address_textview.setText(getAddress());
}
public String getAddress() {
String address1 = "";
String address2 = "";
String city = "";
String state = "";
String country = "";
String county = "";
String PIN = "";
String full_address = "";
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" +"12.9818619" + ","
+ "77.6480391" + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
if (Type.equalsIgnoreCase("street_number")) {
address1 = long_name + " ";
} else if (Type.equalsIgnoreCase("route")) {
address1 = address1 + long_name;
} else if (Type.equalsIgnoreCase("sublocality")) {
address2 = long_name;
} else if (Type.equalsIgnoreCase("locality")) {
// Address2 = Address2 + long_name + ", ";
city = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
county = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
state = long_name;
} else if (Type.equalsIgnoreCase("country")) {
country = long_name;
} else if (Type.equalsIgnoreCase("postal_code")) {
PIN = long_name;
}
}
full_address = address1 +","+address2+","+city+","+state+","+country+","+PIN;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return full_address;
}
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}
}
我需要在MainActivity中使用lat1和lng1变量。
IncomingSms.java
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String body = currentMessage.getMessageBody().toString();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + body);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + body, duration);
toast.show();
StringTokenizer tokenizer = new StringTokenizer(body, ",");
Toast toast1 = Toast.makeText(context, "tokenizer", Toast.LENGTH_SHORT);
toast1.show();
int numberOfTokens = tokenizer.countTokens();
String[] splitArr = new String[numberOfTokens];
splitArr[0] = tokenizer.nextToken();
splitArr[1] = tokenizer.nextToken();
Toast toast2 = Toast.makeText(context, "split", Toast.LENGTH_SHORT);
toast2.show();
Toast toast3 = Toast.makeText(context, splitArr[0], Toast.LENGTH_SHORT);
toast3.show();
Toast toast4 = Toast.makeText(context, splitArr[1], Toast.LENGTH_SHORT);
toast4.show();
String lat=splitArr[0];
String lng=splitArr[1];
double lat1=Double.valueOf(lat);
double lng1=Double.valueOf(lng);
}
答案 0 :(得分:0)
创建一个单独的类
public class Constants {
static long lat1,long1;
public static long getLat1() {
return lat1;
}
public static void setLat1(long lat1) {
Constants.lat1 = lat1;
}
public static long getLong1() {
return long1;
}
public static void setLong1(long long1) {
Constants.long1 = long1;
}
}
从你的广播设置这个值,如Constants.setLat1(lat1),并在你的活动中使用Constants.getLong1()
获取值答案 1 :(得分:0)
创建一个名为 Constant.java
的新类public class Const {
public static int A = 0;
public static String selectedImagePath;
}
然后在你的课程中使用它
public class A extends Activity
{
....
....
Const.A = //whatever;
Const.selectedImagePath = //whatever.;
}
public class B extends Broadcastreceiver
{
Const.A = //whatever;
Const.selectedImagePath = //whatever.;
}
那么你也可以在你的broadcastreceiver课上试试。
答案 2 :(得分:0)
使用Intent
(您需要一个启动另一个Activity
)或Bundle
来通过活动传递数据。