BroadcastReceiver is receiving like 1 of 10 intents - android

On button click I am opening activity(ActionListActivity) and sending intent to IntentService (later this service sends broadCast intent to ActionListActivity). But I am usually receiving only the first intent after launch. Is it real that intent is sent before the receiver is registred?
I want to get data providet by the intentService, and update my UI using it.
Scheme Activity->IntentService->BroadCastReceiver inside ActionListActivity
Activity:
private void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.actions:{
Intent myIntent = new Intent(this, ActionListActivity.class);
this.startActivity(myIntent);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
Intent dataIntent = new Intent(this, DatabaseWorkIntentService.class);
dataIntent.putExtra(Utils.INTENT_SERVICE_INVOKE, Utils.READ_ACTIONS_DATA);
startService(dataIntent);
progressDialog.dismiss();
}
}
}
IntentService:
private void readActionData(){
Log.e("read actions data","data");
List<Action> actionList;
actionList = Action.listAll(Action.class);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Utils.READ_ACTIONS_DATA);
broadcastIntent.putParcelableArrayListExtra(Utils.READ_ACTIONS_DATA, (ArrayList<? extends Parcelable>) actionList);
sendBroadcast(broadcastIntent);
}
ActionListActivity:
public class ActionListActivity extends BaseActivity {
boolean mIsReceiverRegistered = false;
DataBroadcastReceiver receiver;
TextView someTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_list_activity);
this.initToolbarAndDrawerWithReadableName(getString(R.string.our_actions));
someTv = (TextView)findViewById(R.id.someTv);
}
public void someTvTest(Action action){
someTv.append(action.getName());
Log.e("data",action.getName());
}
#Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mIsReceiverRegistered) {
if (receiver == null)
receiver = new DataBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Utils.READ_ACTIONS_DATA);
receiver.setMainActivityHandler(this);
registerReceiver(receiver, filter);
mIsReceiverRegistered = true;
}
}
}
class DataBroadcastReceiver extends BroadcastReceiver{
ActionListActivity activity = null;
ArrayList<Action> list;
public void setMainActivityHandler(ActionListActivity main){
activity = main;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e("reciever","reciev");
list = intent.getParcelableArrayListExtra(Utils.READ_ACTIONS_DATA);
for (Action action:list){
if(activity!=null) {
activity.someTvTest(action);
}
}
}
}

You start activity and service async.
You need to start service inside ActionListActivity and wait for response.

Related

LocalBroadcastManager not receiving broadcasts in a Activity

I am using a LocalBroadcastManager to make broadcast to my activtiy and services using APPLICATION CONTEXT , like this:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
Now Using a Listener in my Service, I am calling broadcastUpdateUICommand() ,like this:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
#Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
And i am receiving the broadcast in my Activity, like this:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp is instance of Application.
CommonForApp is my Application Class.
But in my activity i am not receving any broadcast(the broadcast manager is initialised using application context) .
Can Anyone suggest me why i am not receiving broadcast in my activity? ..
.Thanks in advance !
in activity:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
then you send broadcast:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

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.

Sending Intent from BroadcastReceiver class to currently running activity

I have a class which extends BroadcastReceiver. On receiving a SMS, I would like to pass information to my main activity class to display the text in a box (Append, if already text is present).
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello");
context.startActivity(i);
}
}
MainActivity.java
public class MainActivity extends Activity{
private TextView results;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
}
I have only one activity class (MainActivity.java). However When i do this I get an exception Unable to pause Activity.
You have three ways:
1) You can define your broadcast inside your MainActivity like this:
in onCreate()
registerReceiver(smsReceiver, new IntentFilter(SMS_RECIEVED));
and define smsReciver in MainActivity
private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//you can update textBox here
handler.postDelayed(sendUpdatesToUI, 10);
}
};
define a runnable to update UI
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
update();
}
};
and update method
private void update(String text) {
textView.setText(textView.getText().toString() + text);
}
2) Register a receiver between your Activity and BroadCastReceiver
3) Start your Activity with new Intent to update current open Activity
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("Key", "text");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
UPDATE :
explain method 2
MainActivity.class
in onResume()
registerReceiver(broadcastReceiver, new IntentFilter(SmsReceiver.BROADCAST_ACTION));
in onDestroy()
unregisterReceiver(broadcastReceiver);
local broadCast (broadcastReceiver, in MainActivity.class)
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
String text = intent.getStringExtra("key");
textView.setText(textView.getText().toString() + text);
}
SmsReceiver.class
global attribute
public static final String BROADCAST_ACTION = "your.package.name.displayevent";
private final Handler handler = new Handler();
Intent intent;
Context context;
in onReceive()
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 10);
this.context = context;//you can retrieve context from onReceive argument
this.intent = new Intent(BROADCAST_ACTION);
define two method
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
display();
}
};
private void display() {
intent.putExtra("key", text);
context.sendBroadcast(intent);
}
Modify your code as below.
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, MainActivity.class);
i.putExtra("updatedString","Hello"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
}
}
public class MainActivity extends Activity{
private TextView results;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras!=null){
results = (TextView) findViewById(R.id.results);
results.setVisibility(View.VISIBLE);
results.append(extras.getString("updatedString"));
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//handle your intent here.Note this will be called even when activity first created.so becareful to handle intents correctly.
}
}

Stop service in an activity

I'm using following code to stop my service
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
And this is my service that works indefinitely
public class UsageRecorderService extends IntentService {
public UsageRecorderService() {
super("UsageRecorder");
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
Why does not stop my service?
This code would work
public class UsageRecorderService extends IntentService {
private boolean mStop = false;
public UsageRecorderService() {
super("UsageRecorder");
}
public final Object sLock = new Object();
public void onDestroy() {
synchronized (sLock) {
mStop = true;
}
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
synchronized (sLock) {
if (mStop) break;
}
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
You can use stopService
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
Also I recommend to read Services guide to understand what is going there.
Activity:
sendBroadcast(new Intent(ACTION_STOP));
IntentService
public class UsageRecorderService extends IntentService {
private static final String TAG = "UsageRecorderService";
String ACTION_STOP = "com.xxx.UsageRecorderService.ACTION_STOP";
boolean stop;
public UsageRecorderService() {
super("UsageRecorder");
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
if (ACTION_STOP.equals(intent.getAction())) {
stop = true;
}
}
};
#Override public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(ACTION_STOP);
registerReceiver(receiver, intentFilter);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG,"onHandleIntent");
while (true && !stop) {
Log.i(TAG,"----running----");
//UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
#Override public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.Android stops the service after all start requests have been handled.

Creating my own action for BroadcastReceiver

I have an method like this:
public static boolean checkConnection(){
if(getConnection()!=null){
return true;
}else
return false;
}
I trying to listen to the result of this method throughout my application. Till my application is alive. Only inside my application
How should I create my own action so that in BroadcastReceiver I can listen to this method and show an dialog when it returns false and hide the dialog automatically when it start returning true?
How and what will be the best approach to do this?
public class BroadCastActivity extends Activity implements OnClickListener{
ConnectionReceverLocal mReceverLocal;
Button mSwithcOn,mSwitchOff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broad_cast);
/*Intent intent = new Intent();
intent.setAction("com.broadcast.myconnectionbroadcast");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);*/
mReceverLocal = new ConnectionReceverLocal();
mSwitchOff = (Button)findViewById(R.id.switchoff);
mSwithcOn = (Button)findViewById(R.id.switchon);
mSwitchOff.setOnClickListener(this);
mSwithcOn.setOnClickListener(this);
}
private void sendMessage() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("Connection result Checking Asynctasks", ""+ConnectionProvider.checkConnection());
return ConnectionProvider.checkConnection();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Intent intent = new Intent("com.broadcast.myconnectionbroadcast");
// Add data
intent.putExtra("message", result);
LocalBroadcastManager.getInstance(BroadCastActivity.this).sendBroadcast(intent);
}
}.execute();
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceverLocal);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mReceverLocal,
new IntentFilter("com.alignminds.broadcast.myconnectionbroadcast"));
sendMessage();
}
public class ConnectionReceverLocal extends BroadcastReceiver {
public ConnectionReceverLocal() {
}
#Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder mDBuilder = new AlertDialog.Builder(BroadCastActivity.this);
Boolean intentAction = intent.getBooleanExtra("message", false);
if(intentAction==false)
{
Log.d("Connection is false in broadcast recever", "Connection is false");
if(mDBuilder!=null)
{
mDBuilder.setMessage("No Network");
mDBuilder.create().show();
}
}else {
Log.d("Connection is true in broadcast recever", "Connection is true");
if(mDBuilder!=null)
{
mDBuilder.setMessage("Network Ok");
mDBuilder.create().show();
}
}
}
}
#Override
public void onClick(View v) {
if(v==mSwithcOn)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
if(v==mSwitchOff)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
}
Send a broadcast with whatever action you want like this
Intent intent = new Intent();
intent.setAction("my_fancy_action");
intent.putExtra(EVENT_MESSAGE, message);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Subclass BroadcastReceiver class to listen for broadcasts
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
// Do something
}
Register your receiver to listen to the broadcast
IntentFilter filter = new IntentFilter();
filter.addAction("my_fancy_action");
LocalBroadcastManager.getInstance(context).registerReceiver(myReceiver, filter);

Categories

Resources