BroadCastReceiver not receving data? - java

I have a Broadcast that sends user's LatLng information. In another activity, I have a Broadcast receiver that is supposed to receive this LatLng information and display it on map as heatmap. Heatmaps are working fine but I think the Broadcast is either not being sent or not being received, can't figure out exactly what's the problem. Maybe I am setting these up incorrectly? What I am trying to achieve is to display all users of my app on the map as a heatmap point. Maybe this is an entirely wrong approach for that matter?
Sender:
private void broadcastUserData(String userId, Double longitude, Double latitude) {
Intent intent = new Intent();
intent.putExtra("VRUId", userId);
intent.putExtra("longitude", longitude);
intent.putExtra("latitude", latitude);
intent.setAction("VRUData");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Receiver:
final Map<String, LatLng> map = new HashMap<>();
private void createBroadcastReceiverVRUData() {
// just for testing
map.put("!2321", new LatLng(7.447893883296565, 9.48882099800934));
map.put("!2321", new LatLng(7.44789382565, 9.4888204));
map.put("!2231", new LatLng(7.447780625, 9.489011));
initializeHeatMap(map);
broadcastReceiverVRUData = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String userId = intent.getStringExtra("VRUId");
LatLng gps = new LatLng(
intent.getDoubleExtra("latitude", 0),
intent.getDoubleExtra("longitude", 0));
if (map.containsKey(userId)) {
map.remove(userId);
map.put(userId, gps);
} else {
map.put(userId, gps);
}
initializeHeatMap(map);
Log.d("THIS IS GPS", gps.toString());
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("VRUData");
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiverVRUData, intentFilter);
}
Heatmap:
List<LatLng> list;
private void initializeHeatMap(Map<String, LatLng> map) {
list = new ArrayList<LatLng>(map.values());
Log.d("GPS coordinates", map.values().toString());
HeatmapTileProvider mProvider = new HeatmapTileProvider.Builder().data(list).build();
mMap.addTileOverlay((new TileOverlayOptions()).tileProvider(mProvider));
}

intent.setAction("VRUData") is not the same intentFilter.addAction("VRUDATA") - one is in all caps.

Try First Thing: you can try gmap.clear(); before adding marker on map, might be the issue with old marker can not replace with new marker.
Try Second Thing :
Your receiver look like this in your activity or whatever where you are using.
private BroadcastReceiver receiver;
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// put your stuuf here
Bundle extras = intent.getExtras();
HashMap<String, String> mData;
}
}:

Related

How to start a method from MainActivity in a foreground service

I have got a MainActivity which gets the current location on click of a button. In the activity, and the location is stored with three different methods in
SharedPreferences
An online SQL Database
In a text file on the device
I have another class to start a foreground service (ForegroundService.java) which starts with the click of another button in the MainAcivity and stops with a third button.
My plan is to have regular (1 hour interval) location updates using the ForegroundService and a JobService. So if we click on the StartService-button in the MainActivity the foreground service should start and regularly call the methods from the MainActivity: getCurrentGPSPosition (to get the location), and the three methods to store the information.
The MainActivity works fine. The ForegroundService can be started and stopped bud I do not know how to make it call the methods from the MainActivity.
Here is the code -
ForegroundService.java:
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import static com.example.currentlocation.App.CHANNEL_ID;
public class ForegroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("GPS position tracker")
//.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_gps_fixed_24)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
App.java
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
public class App extends Application {
public static final String CHANNEL_ID = "CurrentLocationServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Current Location Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
In the MainActivity the following parts:
public class MainActivity extends AppCompatActivity {
........
//Backgroundservice
public void startService(View v){
// String input = editTextInput.getText().toString();
Intent serviceIntent = new Intent(this, ForegroundService.class);
// serviceIntent.putExtra("inputExtra", input);
startService(serviceIntent);
}
public void stopService(View v){
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
}
//Method to store in SQL online
public void OnReg() {.......code....}
//Method to save data in SharedPreferences
public void saveData() {.......code....}
//Method to save data in Internal File
public void saveToFile() {.......code....}
//method for GPS request
getCurrentGPSLocation() {.......code....}
}
Has anybody got an idea how to work that out? Or do you need more details? Thanks for your help!
Don't put those functions in MainActivity. If you need them to be called from both the Activity and a Service, put them in a separate class that can be instantiated as needed. If you can't do that because there's data in MainActivity that both need, rethink your architecture- that data won't be available when the job service fires anyway.
OK, first solution is to make a new class (Functions.java) and using an intent to call this class form the MainActivity and then do the location request there and then give the data back to the MainActivity.
Second step would then be to do the same from the foreground service.
The Problem is, the functions class does not get the data from the method. If I put hard-coded strings into the intent, they are transmitted to the MainActivity, so the intent works. So this is only part of the full solution.
Here's the code:
public class Functions extends AppCompatActivity {
//initialize variable
FusedLocationProviderClient fusedLocationProviderClient;
private double ser_Latitude;
private double ser_Longitude;
private String ser_Accuracy;
private String ser_Altitude;
private String currentDateandTime;
private String ser_Location;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Boolean precision = getIntent().getBooleanExtra("precision", true);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(
Functions.this);
getCurrentGPSLocation();
Intent intent = new Intent();
intent.putExtra("latitude", ser_Latitude);
intent.putExtra("longitude", ser_Longitude);
intent.putExtra("accuracy", ser_Accuracy);
intent.putExtra("altitude", ser_Altitude);
intent.putExtra("location", ser_Location);
intent.putExtra("currentDateandTime", currentDateandTime);
setResult(RESULT_OK, intent);
Functions.this.finish();
}
//Force new GPS Location Request
private void getCurrentGPSLocation() {
// get the new location from the fused client
// update the UI - i.e. set all properties in their associated text view items
//Initialize new location request
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(3000)
.setFastestInterval(2000)
.setNumUpdates(1)
;
//Initialize location call back
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
//Initialize location1
Location location1 = locationResult.getLastLocation();
//Set latitude
ser_Latitude = location1.getLatitude();
//Set longitude
ser_Longitude = location1.getLongitude();
//Set Accuracy
double ser_accura1 = location1.getAccuracy();
ser_Accuracy = new DecimalFormat("##.##").format(ser_accura1) + " m";
//Set Altitude
double ser_altit1 = location1.getAltitude();
ser_Altitude = new DecimalFormat("##.##").format(ser_altit1) + " m";
//Get Adress
/* Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(ser_Latitude, ser_Longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String _Location1 = listAddresses.get(0).getAddressLine(0);
//Set Location
//ser_Location = String.valueOf(_Location1);
}
} catch (IOException e) {
e.printStackTrace();
}*/
//Set location as hard-coded string for testing
ser_Location = "London";
//Set Update Time
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy 'um ' HH:mm:ss z");
currentDateandTime = sdf.format(new Date());
}
};
//Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest
, locationCallback, Looper.myLooper());
}
}
The new GPS request is triggered as I can see running the app, but no information is delivered from the method getCurrentGPSLocation() to the intent, which I can see because even the hard-coded location string is not delivered.
This needs revision please.

Unable to view receive SMS within fragment

Hi I wonder if anyone could advise. I have an arduino which is sending GPS coordinates via SMS to my phone. I then need to extract the coordinates and display them as a marker on a map. The map is being implemented as a fragment. Here is my code for the broadcastreceiver class:
public class SmsBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){} }
And within the fragment:
public BroadcastReceiver receiver = new SmsBroadcastReceiver(){
public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null)
{
String number = "";
String message = "";
//---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]);
number = msgs[i].getOriginatingAddress();
message = msgs[i].getMessageBody();
}
//---display the new SMS message---
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
};
I have also registered the receiver:
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
receiver = new SmsBroadcastReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
IntentFilter filter = new IntentFilter();
receiver = new SmsBroadcastReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
I am not getting the toast message displayed onscreen to indicate that the function has run, what have I not understood? I am very new to java and android programming so my understanding is not complete. Thanks in advance.
You are missing action in IntentFilter which should be android.provider.Telephony.SMS_RECEIVED.
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
receiver = new SmsBroadcastReceiver();
getActivity().registerReceiver(receiver, filter);
Also watch out for Runtime Permission above api 23.
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Is there anyway to send data in an intent put extra without starting an activity?

So im getting my data from a web service and using RecyclerView adapter.In RecyclerView.adapter's onBindviewholder method I want to pass the data to the recyclerView in the MainActivity but also pass the data (item) to MyMapsActivity.The thing is the onBindViewholder has setOnClickListener and
setOnLongClickListener as controls that are being used. Is there either a way to send the data(item) using an intent that doesnt start the activity or is there a way I can wire up a new button within the onBindViewholder method because what happens is when the app starts up it goes straight to MyMapsActivity which is expected. Is there a way to control this by either using a new button that can interact with onBindViewholder or is there a way to pass the intent.putExtra without starting the MyMapsActivity.Maybe My understanding is flawed but here is my code for the methods and activities stated:
onBindViewholder
public void onBindViewHolder(DataItemAdapter.ViewHolder holder, int position) {
final DataItem item = mItems.get(position);
try {
holder.titletext.setText(item.getTitle());
holder.companyText.setText(item.getCompany());
holder.cityText.setText(item.getCity());
holder.salarytext.setText(""+ item.getSalary());
holder.descriptionText.setText(item.getDescription());
holder.responsibilityText.setText(item.getResponsibility());
holder.latText.setText(""+ item.getLatitude());
holder.lngText.setText(""+ item.getLongitude());
holder.phoneText.setText(item.getPhone());
holder.provinceText.setText(item.getProvince());
} catch (Exception e) {
e.printStackTrace();
}
//click
holder.mView.setOnClickListener(new View.OnClickListener() {//getting viewholder class and ctor
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext,DetailsActivity.class);
intent.putExtra(ITEM_KEY,item);
mContext.startActivity(intent);
}
});
//long click
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(mContext, "long click: " + item.getTitle(), Toast.LENGTH_SHORT).show();
return false;
}
});
// !!!!!----this is the intent Im talking about----!!!
Intent intent = new Intent(mContext,MyMapActivity.class);
intent.putExtra(ITEM_KEY,item);
mContext.startActivity(intent);
}
My maps method :
public void onMapReady(GoogleMap googleMap) {
final DataItem item = getIntent().getExtras()
.getParcelable(DataItemAdapter.ITEM_KEY); //--------gets intent frm dataItemAdapter
if (item == null) {
throw new AssertionError("null data recived");
}
mapReady = true;
mMap = googleMap;
LatLng latLngToronto = new LatLng(43.733092, -79.264254);
// LatLng latLnghome = new LatLng(43.656729, -79.377162);
CameraPosition target = CameraPosition.builder().target(latLngToronto).zoom(15).tilt(65).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
markerDisplay(item.getTitle(),item.getLatitude(),item.getLongitude());//------maps jobs marker-------new
//add markers and
//instantiate
// mMap.addMarker(mp);
// mMap.addMarker(md);
}
You do not need to call startAcivity method.
There is sendBroadcast method for sharing intent to other components.
String CUSTOM_ACTION = "com.example.YOUR_ACTION";
Intent i = new Intent();
i.setAction(CUSTOM_ACTION)
intent.putExtra(ITEM_KEY,item);
context.sendBroadcast(intent);
Then you can receive your intent with BroadcastReceiver
public class MyReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action!=null && action.equals(CUSTOM_ACTION)){
//do something
}
}
}
register receiver with custom IntentFilter into onCreate method of your activity
IntentFilter filter = new IntentFilter(CUSTOM_ACTION);
registerReceiver(myReceiver, filter);
And do not forget unregister it in onDestroy
unregisterReceiver(myReceiver);
P.S
There are many ways of transferring data between classes and components. It depends on your purpose.
Broadcast receiver with intents are good for data transfer between services and activities and for data transfer between apps.
If you need to have access to data from different places then there are other ways.
If the data needs to be stored on a disk, then the database is suitable.
To store data in RAM, you can use separate class and store this class as a Singleton or into your Application class.

Keep broadcast receiver running after application is closed

I need to keep broadcast receiver running all the time after app has been started.
Here is the code that registers this receiver in the application
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenEventsReceiver();
registerReceiver(mReceiver, filter);
And code for receiver
public class ScreenEventsReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
Log.d("ScreenEventReceiver", "ON");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
Log.d("ScreenEventReceiver", "ON");
}
}
}
You can use a service
In main app start/stop the service
Intent service = new Intent(context, MyService.class);
context.startService(service);
...
Intent service = new Intent(context, MyService.class);
context.stopService(service);
service
public class MyService extends Service
{
private static BroadcastReceiver m_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
unregisterReceiver(m_ScreenOffReceiver);
m_ScreenOffReceiver = null;
}
private void registerScreenOffReceiver()
{
m_ScreenOffReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "ACTION_SCREEN_OFF");
// do something, e.g. send Intent to main app
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(m_ScreenOffReceiver, filter);
}
}
Accepted answer is not an actual answer i think. I will explain what the issue. I think you are testing your app in the Huawie, Oppo, Vivo, Xiomi,asus....... or some devices. With that devices if we close the application they will also close our broadcast receivers. So thats the problem.(To check that use a with pixel nexus emulator). I will explain how to resolve this.``
we would add our app to the protected app list. OS only allow to them to continue broadcast receiver activities.(Copy this array declaration to your code)
private static final Intent[] POWERMANAGER_INTENTS = {
new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
new Intent().setComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")),
new Intent().setComponent(new ComponentName("com.htc.pitroad", "com.htc.pitroad.landingpage.activity.LandingPageActivity")),
new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.MainActivity"))};
Put these code to your onCreate Method. Here i used shared preference for check it only first time of the app open.
`
final SharedPreferences.Editor pref = getSharedPreferences("allow_notify", MODE_PRIVATE).edit(); pref.apply(); final SharedPreferences sp = getSharedPreferences("allow_notify", MODE_PRIVATE)`;
if(!sp.getBoolean("protected",false)) {
for (final Intent intent : POWERMANAGER_INTENTS)
if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert Title").setMessage("Alert Body")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(intent);
sp.edit().putBoolean("protected",true).apply();
}
})
.setCancelable(false)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create().show();
break;
Be careful if you are using Android 4.4.x as there is a bug which kills background services when closing the app. I was testing my app in Android 4.4.2 and I had the same problem. Here there is a detailed explanation:
http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-is-on-the-way/
You cannot receive some broadcast events through components declared in manifest.
These events are
ACTION_BATTERY_CHANGED
ACTION_CONFIGURATION_CHANGED
ACTION_SCREEN_OFF (You are playing with this event)
ACTION_SCREEN_ON (You are playing with this event)
ACTION_TIME_TICK
Reference https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_ON
So in your specific events,
you will have to create a Service & you will have to register your event explicitly in service onCreate() with with Context.registerReceiver().
For other events,
entry in manifest is sufficient.
If you declare BroadcastReceiver in the Manifest, it will always be active and be called even if the application is closed/stopped
You could start a service that is running in the foreground. That's the only way to ensure (mostly) that your app will get the events. There is still a chance that your foreground service could get killed in times of crazy memory pressure from the OS (so it's not foolproof). If you start a service in the foreground, the user will see a persistent notification to know that it is always running, though.
So the moral of the story is, do you really need to monitor the screen off/on events at all times? The reason that they force you to register a receiver not in the manifest is that they don't want people to always be monitoring these events and slowing down the device. What are you trying to accomplish?
The best way I found is the Foreground Services. I registered my BroadcastReceiver from my Service only under the onStartCommand() as I want my service needs to run always, I returned START_STICKY
This way, my broadcast receiver survives even after terminating the app from stack.
Used below code in my service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("rht", "Received start id " + startId + ": " + intent);
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
This is how I started my service
Intent serviceIntent = new Intent(this, SpeechServiceForeground.class);
ContextCompat.startForegroundService(this, serviceIntent);

Adding a list of scan results from Wifi to an intent and retrieving from a broadcast receiver?

I want to add a list as a parameter to pass into an intent and then receive it from a broadcast listener, but I'm having some trouble. I cannot figure out how to put this List into the Intent as an extra, or retrieving the list from it. I can get into the broadcast receiver.
//In my Main File: Everthing is registered and working.
IntentFilter startUsingScanResults = new IntentFilter("StartUsingScanResults");
c.registerReceiver(serviceConsume.ScanResultReceiver, startUsingScanResults);
List<ScanResult> scanResults = Some values;
Intent intent = new Intent();
intent.setAction("StartUsingScanResults");
// Then Need to put the List<ScanResults> into the intent.
// ie: intent.putExtra("MyResults", scanResults);
Context.sendBroadcast(intent);
// My broadcast receiver that should have the list inside it.
public BroadcastReceiver ScanResultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
// Need something here to get the list
// ie: List<ScanResult> scanResults = extras.getBundle("MyResults");
}
};
Hopefully I am clear with this question. I just need to put the list into and get the List from the bundle (or intent).
A ScanResult is in the format of ["","","","","","",""] if that helps. So I guess it might be similar to a multidimensional array.
Any help is appreciated! Thanks
I've figured it out. I like simple solutions, and this is pretty much as simple as it gets.
intent.putParcelableArrayListExtra("ScanResults", (ArrayList) scanResults);
And Add this to the Broadcast receiver
ArrayList scanResults = extras.getParcelableArrayList("ScanResults");
So the end result is:
//In my Main File:
IntentFilter startUsingScanResults = new IntentFilter("StartUsingScanResults");
c.registerReceiver(serviceConsume.ScanResultReceiver, startUsingScanResults);
List<ScanResult> scanResults = Some values;
Intent intent = new Intent();
intent.setAction("StartUsingScanResults");
intent.putParcelableArrayListExtra("ScanResults", (ArrayList<? extends Parcelable>) scanResults);
Context.sendBroadcast(intent);
// And my broadcast receiver
public BroadcastReceiver ScanResultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
ArrayList<ScanResult> scanResults = extras.getParcelableArrayList("ScanResults");
}
};
Hopefully this helps out someone in a similar situation.

Categories

Resources