将来自BroadcastReceiver类的字符串数据传递给Android活动
问题描述:
我正在开发一个Android应用程序,它具有在应用程序在用户启用或禁用GPS的情况下运行时的功能。我收到广播并使用界面在活动上显示状态。将来自BroadcastReceiver类的字符串数据传递给Android活动
GpsLocationReceiver
public class GpsLocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(context, "GPS Disabled", Toast.LENGTH_SHORT).show();
}
}
我注册这个广播接收器中的Manifest.xml
<receiver android:name=".GpsLocationReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
答
步骤1
private void sendLocationBroadcast(Intent intent) {
SharedPreferences pref = getSharedPreferences(Data.SHARED_PREF_NAME, 0);
totaldisplacement = Double.parseDouble(pref.getString(Data.SP_TOTAL_DISTANCE_COVER_TILL, ""));
intent.putExtra(Data.SP_TOTAL_DISTANCE_COVER_TILL, totaldisplacement);
intent.putExtra("latitude", currentlat);
intent.putExtra("longitude", currentlong);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.e("Data", "" + rikshawspeed + " " + currentlat);
}
步骤2
private void dataSendToMainActivity() {
Intent intent = new Intent("speedExceeded");
sendLocationBroadcast(intent);
}
步骤3
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
distanceFromService = intent.getDoubleExtra(Data.SP_TOTAL_DISTANCE_COVER_TILL, 55);
Double currentLatitude = intent.getDoubleExtra("latitude", 0);
Double currentLongitude = intent.getDoubleExtra("longitude", 0);
// Toast.makeText(getApplicationContext(), "speed " + distanceFromService + "\n" + "Lat Long " + "\n" + currentLatitude + "\n" + currentLongitude, Toast.LENGTH_SHORT).show();
// ... react to local broadcast message
Log.e("Main", "" + distanceFromService);
}
};
步骤4
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("speedExceeded"));
答
-
在活动
public void onResume() { registerReceiver(mGattUpdateReceiver, new IntentFilter().addAction("ACTION_DATA_AVAILABLE"); return intentFilter;); } public void onPause(){ unregisterReceiver(mGattUpdateReceiver); } private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if(action.equals("ACTION_DATA_AVAILABLE")) { } } };
2. 在BroadcastReciver onReciever()
final Intent intent = new Intent("ACTION_DATA_AVAILABLE"); intent.putExtra("KEY","YourString"); sendBroadcast(intent);
什么是你的问题?你面临的问题是什么? –
我想将数据从BroadcastReceiver传递给一个活动。 –
这将帮助你https://stackoverflow.com/questions/9137477/passing-data-from-broadcast-receiver-to-another-activity –