infinitly execution while send broadcast - android

I want to use
context.sendBroadcast(intent, receiverPermission);
in my application
but I don't know to pass receiverPermission parameter in function and also how to set in manifest file
please any body help me
I want to show you my source code
public class LocationReceiver extends BroadcastReceiver {
public static final String BROADCAST_ACTION = "LOCATION_CHANGE";
#Override
public void onReceive(Context context, Intent intent) {
intent.setAction(BROADCAST_ACTION);
Bundle b = intent.getExtras();
Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
Logger.debug("Loc:"+loc);
if(loc != null){
doBroadCast(context,intent,loc);
}
}
public void doBroadCast(final Context context,final Intent i1,final Location loc){
Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Logger.debug("LocationReceiver->sendLocation update broadcast");
i1.putExtra("Latitude", loc.getLatitude());
i1.putExtra("Longitude", loc.getLongitude());
context.sendBroadcast(i1,null);
}
});
}
}
and on activity I have write
#Override
protected void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(LocationReceiver.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
UpdateUI(intent);
}
};
private void UpdateUI(Intent i){
Double Latitude = i.getDoubleExtra("Latitude",0);
Double Longitude = i.getDoubleExtra("Longitude",0);
showMap(Latitude, Longitude);
}
Now my problem is when it sendbroadcast it execute infinitly doBroadcast function(), please help me to come out.

Check after intent.setAction(BROADCAST_ACTION); that the action is really set to BROADCAST_ACTION
Check if you have registered this BroadcastReceiver with the action BROADCAST_ACTION in the <intent-filter> ( if it is, then that s why you have that infinite loop)

Related

BroadcastReceiver not receiving broadcast from IntentService in Android

I'm sending a progress value like int progress = 10 via Broadcast from IntentService to display the progress of uploading file.
protected void onHandleIntent(Intent intent) {
broadcastIntent = new Intent();
broadcastIntent.setAction(SendList.mReceiver.TEST);
try {
broadcastIntent.putExtra("Count",mArraylist.size());
[...uploading data...]
for (int i = 0; i < mArrayList.size(); i++) {
broadcastIntent.putExtra("progress", i);
sendBroadcast(broadcastIntent);
//...
}
}
So in my Activity I register the receiver but it is never called.
public class SendList extends Activity {
TextView textResult;
ProgressBar progressbar;
boolean mIsReceiverRegistered = false;
BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.sendlist);
textResult= (TextView)findViewById(R.id.maxFragments);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onResume() {
super.onResume();
if(!mIsReceiverRegistered) {
if (receiver == null)
receiver = new FragmentReceiver();
registerReceiver(receiver,new IntentFilter(mReceiver.TEST));
mIsReceiverRegistered = true;
}
}
#Override
public void onPause() {
super.onPause();
if(mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
private void updateUI (Intent intent) {
progressbar.setProgress(intent.getIntExtra("progress", 0));
}
public class mReceiver extends BroadcastReceiver {
public static final String TEST = "upload";
#Override
public void onReceive(Context context, Intent intent) {
int count = intent.getIntExtra("Count",0);
progressbar.setMax(count);
textResult.setText(count);
updateUI(intent);
}
}
Where could be the problem? What am I doing wrong? Have I forgotten something?
Thanks for any help!
Kind Regards!
try to register you receiver as below -
IntentFilter filter = new IntentFilter();
filter.addAction(SendList.mReceiver.TEST);
registerReceiver(receiver,filter);
while broadcasting you are sending action as below
broadcastIntent.setAction(SendList.mReceiver.TEST);
and when you register it is different.
registerReceiver(receiver,new IntentFilter(FragmentReceiver.TEST));
Your action should be same while sending and receiving.
Hope this will help you.

How to receive values from an IntentService in another IntentService?

I have this IntentService (HttpService) which fetches raw json data from a webservice:
public class HttpService extends IntentService {
public static final String BROADCAST_ACTION = "com.example.HttpService";
public HttpService() {
super("HttpService");
}
#Override
protected void onHandleIntent(Intent intent) {
//code to get a String with jsonData
//Then I send a broadcast
Intent broadcastHttpResponseIntent = new Intent();
broadcastHttpResponseIntent.setAction(BROADCAST_ACTION);
broadcastHttpResponseIntent.putExtra("jsonData", jsonData);
sendBroadcast(broadcastHttpResponseIntent);
}
}
Now from the IntentService that uses HttpService I'm trying to get the broadcast:
public class RestaurantModel extends IntentService {
public static final String BROADCAST_ACTION = "com.example.RestaurantModel";
public RestaurantModel() {
super("RestaurantModel");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.v("RestaurantModel", "onHandleIntent");
BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("RestaurantModel", "onReceive");
String jsonResponse = intent.getStringExtra("jsonData");
}
};
Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
startService(getRestaurantsJsonIntent);
registerReceiver(httpBroadcastReceiver, new IntentFilter(HttpService.BROADCAST_ACTION));
}
}
SO I'm getting this error:
RestaurantModel has leaked IntentReceiver com.example.RestaurantModel$1#42374590 that was originally registered here. Are you missing a call to unregisterReceiver()?
So I tried unregistering the Receiver but it seems to need a Context to unregister the receiver.
How to receive values from an IntentService into another IntentService?
The best answer is: have only one IntentService.
The next-best answer is: get rid of the broadcast stuff entirely, and have the first IntentService call startService() to kick off the second IntentService.
Agree with #CommonsWare, in case you want to use BroadcaseReceiver inside of an IntentService, register it in the onCreate method and unregister it in the onDestroy method.
public class RestaurantModel extends IntentService {
public static final String BROADCAST_ACTION = "com.example.RestaurantModel";
private BroadcastReceiver httpBroadcastReceiver;
public RestaurantModel() {
super("RestaurantModel");
}
#Override
public void onCreate() {
super.onCreate();
httpBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("RestaurantModel", "onReceive");
String jsonResponse = intent.getStringExtra("jsonData");
}
};
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(httpBroadcastReceiver);
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(httpBroadcastReceiver);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.v("RestaurantModel", "onHandleIntent");
Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
startService(getRestaurantsJsonIntent);
}
}

How to refresh a ListView from a BroadcastReceiver?

If I call notifyDataSetChanged() on the custom adapter associated to my ListView, all the views should refresh themself (getView() will be called).
Now I have a BroadcastReceiver that is listening to an event. When the event fires, the ListView must be refreshed. How can I achieve this?
Thanks!
If you refresh listview from receiver you'll have code like this:
BroadcastReceiver br;
public final static String BROADCAST_ACTION = "BROADCAST_ACTION";
br = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//code refreshing...
}
};
IntentFilter intFilt = new IntentFilter(BROADCAST_ACTION);
registerReceiver(br, intFilt);
And you call it with code:
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
If you need the refresh to be another action you just need to add (after action):
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
As requested, please see the sample code below:
public interface OnDataUpdateListener {
void onDataAvailable(ArrayList<String> newDataList);
}
public class MyTestReceiver extends BroadcastReceiver {
public static final String DATA_LIST = "DATA_LIST";
private OnDataUpdateListener mDataUpdateListener = null;
public MyTestReceiver(OnDataUpdateListener dataUpdateListener) {
mDataUpdateListener = dataUpdateListener;
}
#Override
public void onReceive(Context ctx, Intent intent) {
// assuming data is available in the delivered intent
ArrayList<String> dataList = intent.getSerializableExtra(DATA_LIST);
if (null != mDataUpdateListener) {
mDataUpdateListener.onDataAvailable(dataList);
}
}
}
public class MyActivity extends FragmentActivity implements OnDataUpdateListener {
public static final String ACTION_DATA_UPDATE_READY = "ACTION_DATA_UPDATE_READY";
private MyTestReceiver mTestReceiver = null;
private <SomeAdapterClass> mAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// other required initialization
mTestReceiver = new MyTestReceiver(this);
}
#Override
public void onResume() {
super.onResume();
if (null != mTestReceiver) {
registerReceiver(mTestReceiver, new IntentFilter(ACTION_DATA_UPDATE_READY));
}
}
void onDataAvailable(ArrayList<String> newDataList) {
// assuming you want to replace existing data and not willing to append to existing dataset
mAdapter.clear();
mAdapter.addAll(newDataList);
mAdapter.notifyDataSetChanged();
}
}
In the code where your data is updated, fire off a message signalling that data has been changed...
(You will need access to either the Activity or the Application context to do this)
Intent intent = new Intent("ListViewDataUpdated");
LocalBroadcastManager.getInstance(context.sendBroadcast(intent));
Then just catch the catch the message using the following code in your activity, and tell your ListAdapter to update...
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
myListAdapter.notifyDataSetChanged();
}
};
#Override
public void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("ListViewDataUpdated"));
myListAdapter.notifyDataSetChanged();//in case our data was updated while this activity was paused
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
Credit: adapted from Vogella
LocalBroadcastManager.getInstance(context.sendBroadcast(intent));
change to
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
I might be wrong but it works for me...

Get intent from broadcast receiver to activity

I want my activity class to receive an intent from broascast Receiver (example START_TALKING, STOP_TALKING). And when I receive that intent, I want to check what action was being passed. How can I do this. My receiver is in separate class, it's public.
Here's my code
public void onReceive(Context context, Intent intent)
{
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
if (action == KeyEvent.ACTION_DOWN)
// here I want to notify my activity class (e.g. startActivity? I don't know)
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// here I want to notify my activity class (e.g. startActivity? I don't know)
}
}
}
I really need your help guys tnx.
Here is my solution, in my project, hope it'll help you:
you should type this:
// put your action string in intent
Intent intent = new Intent("com.example.myproject.ADD_ITEM_BASKET");
// start broadcast
activity.sendBroadcast(intent);
public class Myclass extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// creating and register receiver
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
// your receiver class
class Receiver extends BroadcastReceiver
{
// catch messages from intent
#Override
public void onReceive(Context context, Intent intent) {
if("com.example.myproject.ADD_ITEM_BASKET".equals(intent.getAction().toString()))
{
// do something
}
else if("com.example.myproject.DELETE_ITEM_BASKET".equals(intent.getAction().toString()))
{
// do something
}
}
}
}
You can use putExtra() in your BroadcastReceiver's onReceive().
/**
* #author Skylifee7 on 23/06/2017.
* TemplateResultReceiver.java
*/
public class TemplateResultReceiver extends BroadcastReceiver {
private static final String TAG = "BleshTemplate";
public static final String EXTRA_MESSAGE = "TRANSACTION_MESSAGE";
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (intent.getAction().equals(BleshConstant.BLESH_TEMPLATE_RESULT_ACTION)) {
String actionType = intent.getStringExtra(BleshConstant.BLESH_ACTION_TYPE);
String actionValue = intent.getStringExtra(BleshConstant.BLESH_ACTION_VALUE);
if (actionType != null && actionValue != null) {
switch (actionType) {
case "MENU": sendMessage(actionValue);
/*
You may want to increase the case possibilities here, like below:
case: "ADMOB"
case: "VIRTUAL_AVM"
case: "SMART_CAR_KEY"
*/
default: sendMessage(actionValue);
}
}
}
}
private void sendMessage(String actionValue) {
Intent intent = new Intent(mContext.getApplicationContext(),TransactionActivity.class);
intent.putExtra(EXTRA_MESSAGE, actionValue);
mContext.getApplicationContext().startActivity(intent);
}
}
And in your Activity class' onCreate() method:
/**
* #author Skylifee7 on 24/06/2017.
* TransactionActivity.java
*/
public class TransactionActivity extends AppCompatActivity {
private String bleshKey;
private String TAG = "Transaction_Activity";
private String amount;
private String isSuccessful; //may be cast to boolean type.
private double latitude, longitude;
private LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
requestPermission();
initLocationService();
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
bleshKey = intent.getStringExtra(BleshTemplateResultReceiver.EXTRA_MESSAGE);
ImageButton paymentBtn = (ImageButton) findViewById(R.id.buttonPay);
final EditText editTextAmount = (EditText) findViewById(R.id.editTextAmount);
paymentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
amount = editTextAmount.getText().toString();
callApiService();
}
});
}
}
You have to register the receiver... Follow this example..
public class MyActivity extends Activity {
private BroadcastReceiver myBroadcastReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// your onreceive code here
}
});
...
public void onResume() {
super.onResume();
....
registerReceiver(myBroadcastReceiver, intentFilter);
}
public void onPause() {
super.onPause();
...
unregisterReceiver(myBroadcastReceiver);
}
...
}

sending intent extras from service to activity

I have a service that listens for (ON_BATTERY_CHANGE), then onReceive service sends a Broadcast to My MainActivity. The problem is that I somehow can't get them from service to my main activity. Code: Main Activity:
public class MainActivity extends Activity
private BroadcastReceiver batteryReceiverService;
private TextView text2;
....
protected void onCreate(Bundle savedInstanceState) {
text2=(TextView)findViewById(R.id.TV_text2);
batteryReceiverService = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
text2.setText("left: "+intent.getStringExtra("H")+" hours "+intent.getStringExtra("M")+" minute(s)");
Log.e("text2","text2 HHH " +intent.getStringExtra("H")); //log shows 0
Log.e("text2","text2 MMM " +intent.getStringExtra("H")); // log shows 0
}
};
registerReceiver(batteryReceiverService, new IntentFilter(UltimateBatterySaverService.BROADCAST_ACTION));
....
#Override
protected void onDestroy() {
unregisterReceiver(batteryReceiverService);
super.onDestroy();
}
Service:
public class UltimateBatterySaverService extends Service {
private Intent intent;
static final String BROADCAST_ACTION = "lt.whitegroup.ultimatebatterysaver";
private BroadcastReceiver batteryLevelReceiver;
....
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryLevelReceiver);
super.onDestroy();
}
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryLevelReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
// Receiving data, calculating and etc
averageChargingH=timeAllInHours;
averageChargingM=timeAllInMinutes;
// to put extras and send broadcast
does();
......
public void does(){
String strLong = Long.toString(averageChargingH);
String strLong2 = Long.toString(averageChargingM);
Log.e("cccccc","strLong h "+strLong); // getting good value not 0(everything ok)
Log.e("cccccc","strLong2 m"+strLong2); // getting good value not 0(everything ok)
intent.putExtra("H", strLong);
intent.putExtra("M", strLong2);
sendBroadcast(intent);
}
Any ideas why my information is not transfered correctly?
The does() method seems to be using variables in the same scope as onReceive so I'm guessing that the intent variable in does() is actually the Intent passed in from onReceive.
Try adding some logging before sending the broadcast to check if the action of the intent is correct, or simply create the broadcast intent in the onReceive method and name it intent2.

Categories

Resources