Broadcast Receiver inside Activty not working - android

I am working on an application that display the messages , for that i am using BroadcastReceiver inside my activity and i am trying to refresh the listview inside onReceive method , but onReceive is not getting call some how please help me with this.
public class MessageActivity extends BaseActivity {
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
Toast.makeText(getApplicationContext(), "Inside Reciver",Toast.LENGTH_SHORT).show();
getSMSCursorCount();
loadInitialMessages();
}
};
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.messageinbox);
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(1000);
registerReceiver(mMessageReceiver, intentFilter);
Log.d("This is onResume method ","<<<<<<<<< onResume <<<<<<<<<");
try {
getSMSCursorCount();
loadInitialMessages();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause()
{
super.onPause();
try {
unregisterReceiver(mMessageReceiver);
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Receiver not registered")) {
// Ignore this exception. This is exactly what is desired
Log.w(TAG,"Tried to unregister the reciver when it's not registered");
} else {
// unexpected, re-throw
throw e;
}
}
Log.d("This is onPause method ","<<<<<<<<< onPause <<<<<<<<<");
}

You have to write separate broadcast receiver class by extending BroadcastReceiver and declare it in your manifest file with intentfilter. Override the onReceive method and call your activity there.In oncreate of activity refresh yor listview if the intent is from broadcast receiver.
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("inside message receiver... ");
Intent popupintent = new Intent(context,ShowNotificationDialog.class);
popupintent.putExtra("from", "broadcast");
context.startActivity(popupintent);
}
public class ShowNotificationDialog extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
String fromString = i.getStringExtra("from");
if(from != null)
{
if(from.equals("from"))
// refresh your listview
}
}
}
In manifest:
<receiver android:name=".MessageReceiver" >
<intent-filter>
<action android:name="broadcast action" />
</intent-filter>
</receiver>

Related

Broadcast Receiver "on recieve" method not been called?

I Have three activities
On activity A i register the broadcast receiver ,then i go to activity B from there i go to activity C.
and finally onBackPressed of activity c ,i send the broadcast
but onReceive is not called
My first Activity
private MyBroadCastReceiver myRecevier = new MyBroadCastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frag=new Intent(MainActivity.this,Activity2.class);
//frag.putExtra("Limit", foo);
startActivity(frag);
// }
}
});
}
#Override
protected void onResume() {
super.onResume();
//Register the activity to the broadcast receiver
registerReceiver(myRecevier, new IntentFilter(MyBroadCastReceiver.ACTION));
}
#Override
protected void onPause() {
super.onPause();
//Unregister the activity from the broadcast receiver. Good practice ;)
unregisterReceiver(myRecevier);
}
public class MyBroadCastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.uberrueco.mybroadcastreceiver.receivers";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadCastReceiver", "received");
Toast.makeText(context,"Received "+intent.getStringExtra("editText"), Toast.LENGTH_LONG).show();
}
}
}
Second activity has nothing but an intent to activity 3
Third Activity
public class Activity3 extends Activity {
EditText etReceivedBroadcast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity3);
etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(this, MyIntentService.class);
intent.putExtra("editText", etReceivedBroadcast.getText().toString());
startService(intent);
}
}
and finally my IntentService class
public class MyIntentService extends IntentService{
public MyIntentService(){
super("MyIntentService");
}
public MyIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "handling intent...");
//Intent created for broadcasting
Intent intentBroadCast = new Intent();
//Filter the broadcast to the action desired
intentBroadCast.setAction(MyBroadCastReceiver.ACTION);
intentBroadCast.putExtra("editText", intent.getStringExtra("editText"));
//Send the broadcast :D
sendBroadcast(intentBroadCast);
}
}
You are calling unregisterReceiver in onPause of MainActivity . So you are not recieving the broadcast.
Move register to onCreate and unregister to onDestroy of your MainActivity.
if your onHandleIntent() was called then you should try like.
Intent intentBroadCast = new Intent(MyBroadCastReceiver.ACTION);
intentBroadCast.putExtra("editText", intent.getStringExtra("editText"));
//Send the broadcast :D
sendBroadcast(intentBroadCast);
make changes like below code
private MyBroadCastReceiver myRecevier = new MyBroadCastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the activity to the broadcast receiver
this.registerReceiver(myRecevier, new IntentFilter(MyBroadCastReceiver.ACTION));
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frag=new Intent(MainActivity.this,Activity2.class);
//frag.putExtra("Limit", foo);
startActivity(frag);
// }
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
//Unregister the activity from the broadcast receiver. Good practice ;)
this.unregisterReceiver(myRecevier);
}
#Override
protected void onPause() {
super.onPause();
//Unregister the activity from the broadcast receiver. Good practice ;)
unregisterReceiver(myRecevier);
}
public class MyBroadCastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.uberrueco.mybroadcastreceiver.receivers";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadCastReceiver", "received");
Toast.makeText(context,"Received "+intent.getStringExtra("editText"), Toast.LENGTH_LONG).show();
}
}
}
u need to use like this this.unregisterReceiver() and this.registerReceiver()

LocalBroadcastManager not working as expected

In my Application I have to notify my Activity from IntentService class .
For that purpose I am using LocalBroadcastManager. But I am not receiving anything in the onReceive of my Broadcast Receiver. Here is what I have written.
In my BaseActivity I have registered my receiver.
public class BaseActivity extends FragmentActivity implements App {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(custom-event-name));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("Overlay Message" +bundle.getString("message"));
}
};
}
I am sending a local broadcast from my RegisterAlarmIntentService class.
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
public RegisterAlramIntentService() {
super("AlarmService");
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Intent localIntent = new Intent(custom-event-name);
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
onHandleIntent() method is called. But nothing is received in onReceive() of my receiver.
Please Help. Thanks in advance!!
Try
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
Intent localIntent;
public RegisterAlramIntentService() {
super("AlarmService");
localIntent = new Intent(custom-event-name);
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
Also in manifest :
<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>
See this

How can i correctly unregister a receiver out of another activity?

i got trouble unregistering my receiver out of another activity. here it is:
Starting/Register the BroadcastReceiver in my launching Activity A.
Activity A:
public class ActivityA extends Activity {
private PowerButtonReceiver mPowerButtonReceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getPowerButtonReceiver() == null)
{
mPowerButtonReceiver(new PowerButtonReceiver());
registerReceiver(mPowerButtonReceiver, new IntentFilter("android.intent.action.SCREEN_ON"));
}
}
public void unregister() {
try {
unregisterReceiver(mPowerButtonReceiver);
} catch (NullPointerException e) {
e.printStackTrace();
}
if (mPowerButtonReceiver == null) {
Log.i(TAG,"unregistered PowerButtonReceiver!");
}
}
then i start Activity B inside the onReceive()-method of my receiver.
After this i step into the onCreate()-method of Activity B, do my stuff and at the end of onCreate() i want to unregister the BroadcastReceiver:
Activity B: (--> android:launchMode="singleTop")
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
[...do my stuff...]
//un-register PowerButtonReceiver --> call in Activity A
MainActivity m = new MainActivity();
m.getParent();
m.unregister();
}
my last line starts the call for unregister(), but there the Receiver is null and it looks like it is not getting the reference for it. Also the Receiver does not get unregistered and is still listening. I am pretty sure that my error is in doi9ng the reference/call; but i don't get how to do it right :/
What am i missing here? Can someone help me?
Pass your Activity A context to Activity B through intent.putExtra() method . Then instead of doing MainActivity m = new MainActivity(); do MainActivity m = ((MainActivity)(passedContext));.
I have tried something like this succesfully, see if this helps: I have a HeadSetTesTActivity , a Headsetconnectorreciever, ActivityB.
HEADSETTESTACTIVITY.JAVA
`public class HeadsettestActivity extends Activity {
/** Called when the activity is first created. */
Headsetconnectorreciever r;
static HeadsettestActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity=this;
Log.d("Inside activity ", "before broadcast reciever registered");
r = new Headsetconnectorreciever();
registerReceiver(r, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
Log.d("Inside activity ", "after broadcast reciever registered");
}
public void unregister() {
try {
if(r!=null){
unregisterReceiver(r);
Log.i("HeadsettestActivity","Inside unregister ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if (r == null) {
Log.i("HeadsettestActivity","unregistered PowerButtonReceiver!");
}
}
}`
Headsetconnectorreciever
`public class Headsetconnectorreciever extends BroadcastReceiver {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Inside broadcast reciever ", "Inside onrecieve");
// TODO Auto-generated method stub
if (intent.hasExtra("state")){
Log.d("Inside broadcast reciever ", "hasstate");
if (headsetConnected && intent.getIntExtra("state", 0) == 0){
headsetConnected = false;
Log.d("Inside broadcast reciever ", "disconnected");
Toast.makeText(context, "Headset is disconnected", Toast.LENGTH_SHORT).show();
}
else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
Log.d("Inside broadcast reciever ", "disconnected");
headsetConnected = true;
Intent intent2=new Intent(context, ActivityB.class);
context.startActivity(intent2);
}
}
}
}`
and finally my ACTIVITY B
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "Headset is connected", Toast.LENGTH_SHORT).show();
HeadsettestActivity a = HeadsettestActivity.activity ;
a.unregister();
}
}
The code actually worked.
Since you are not closing the other activity i would had sent intent to Activity A,
Activity B
boolean unregister = true;
Intent intent = new Intent(this, Activity_A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("unregister",unregister);
startActivity(intent);
on Activity A you override onNewIntent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) {
if (intent.getBooleanExtra("unregister", false)) {
unregister();
}
}
}

android: how to get broadcasted messages from service when activity is in background

I have a service and an activity. in service I broadcast messages received from network and in the activity show these messages. this works fine. but all messages will lost when the activity is in the background.
How can I get last messages(if exists) from server, in activity onResume(or onCreate)?
EDIT :
in service:
public class server extends Service implements Runnable
{
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onStart(Intent intent, int startID)
{
//initializing socket and begining listen
new Thread(this).start();
}
public void run()
{
String readed;
while (true)
{
if(reader == null) continue;
try
{
if ((readed = reader.readLine()) != null)
{
Intent intent = new Intent(SEND_DATA_INTENT);
intent.putExtra("type", "message");
intent.putExtra("content", readed.substring(1));
sendBroadcast(intent);
Thread.sleep(100);
}
}
catch (Exception ee) { }
}
}
}
and in activity:
public class menhaj extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
#Override
protected void onResume()
{
if (dataUpdateReceiver == null) dataUpdateReceiver = new DataReciver();
IntentFilter intentFilter = new IntentFilter(server.SEND_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);
super.onResume();
};
#Override
protected void onPause()
{
if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);
super.onPause();
};
private class DataReciver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(server.SEND_DATA_INTENT))
{
Bundle bdl = intent.getExtras();
String type = bdl.getString("type");
if (type.equals("message"))
{
String message = bdl.getString("content");
db.addMessage(message);
showMessage(message);
}
}
}
}
}
If that activity is in the background, the user probably doesn't want to see messages from it. Show notifications from your services instead. Generally, an activity should de-register itself onPause() and register again onResume() when it comes back to the foreground.
I would declare BroadcastReceivers , those can receive messages and bring back to from your avtivity / app

Dynamically register/unregister a broadcast receiver in android

I want to dynamically register and unregister my receiver class with the broadcast:
"android.net.wifi.STATE_CHANGE"
This works very well if I do this in the manifest. But this makes it static. I want to do it dynamically in the activity class. What is its correspondent command in the activity class?
This is what my code is...
and I am getting a problem because of registering and unregistering(multiple times) my receiver(which is starting a service).
public class startScreen extends Activity {
/** Called when the activity is first created. */
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.MyService");
context.startService(serviceIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.initial);
final IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.STATE_CHANGE");
Button button = (Button) findViewById(R.id.button1);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
try {
...some code...
if (bool == true) {
toggleButton.setChecked(true);
this.registerReceiver(receiver, filter);
} else
toggleButton.setChecked(false);
} catch (Exception e) {
Log.e("Error", "Database", e);
} finally {
...
}
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((toggleButton.isChecked())) {
getBaseContext().registerReceiver(receiver, filter);
} else {
if (receiver != null) {
getBaseContext().unregisterReceiver(receiver);
receiver = null;
}
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (bool == true) {
if (receiver == null)
this.registerReceiver(receiver, filter);
}
}
#Override
protected void onPause() {
super.onPause();
if (receiver != null) {
this.unregisterReceiver(receiver);
receiver = null;
}
}
}
The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don't leave your application.
The following example shows an activity which registers for a customer event called my-event.
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
// This method is assigned to button in the layout
// via the onClick property
public void onClick(View view) {
sendMessage();
}
// Send an Intent with an action named "my-event".
private void sendMessage() {
Intent intent = new Intent("my-event");
// add data
intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
use the below methods to register/unregister your receiver:
registerReceiver(BroadcastReceiver receiver, new IntentFilter("android.net.wifi.STATE_CHANGE"));
unregisterReceiver(BroadcastReceiver receiver);
For reference have a look at this
Don't add dynamic broadcast receiver in onReceive on broadcast file. Add it on first activity or main activity of your application. If you needed it only when your application is open. But if you need it always received response just added it on manifest file
Register dynamic broadcast receiver on main activity
MyReceiver reciver;
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
reciver = new MyReceiver();
registerReceiver(reciver, intentFilter);
}
Unregister that broadcast receiver on activity stop or closed
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(reciver);
}
Perhaps I'm a bit too late, but the problem lies on the fact that you are setting the receiver = null in your onPause method, and then never setting it again. You are also trying to register it in your onResume method but only if it is null, which makes no sense too.
You should change the logic where you set/test the null value of the receiver, to instead just use a boolean variable to keep track of the receiver status (if it's registered or not).
public void registerBroadcastReceiver(View view) {
this.registerReceiver(broadCastReceiver, new IntentFilter(
"android.intent.action.TIME_TICK"));
}
public void unregisterBroadcastReceiver(View view) {
this.unregisterReceiver(broadCastReceiver);
}

Categories

Resources