I've tried the examples from many different answers to similar questions, but nothing works. When I press the back button, I get "Broadcasting message" in the log but not "Broadcast received". Why?
public class MainActivity extends ActionBarActivity
implements ContactsFragment.ContactListener {
private IntentFilter filter;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Broadcast received");
}
};
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
filter = new IntentFilter(Constants.BROADCAST_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}
#Override
public void onBackPressed() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent(Constants.BROADCAST_ACTION);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
if (!pane.isOpen()) {
pane.openPane();
} else {
finish();
}
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onPause();
}
}
Related
I can't stop receiving broadcasts. Why?
This is the code I have:
public class MainActivity extends AppCompatActivity {
BroadcastReceiver br = new CustomReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver br = new CustomReceiver();
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
this.registerReceiver(br, filter);
}
#Override
protected void onStart() {
super.onStart();
if(!br.isOrderedBroadcast())
this.registerReceiver(br, filter);
}
#Override
protected void onStop() {
super.onStop();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
#Override
protected void onPause() {
super.onPause();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
#Override
protected void onResume() {
super.onResume();
if(!br.isOrderedBroadcast())
this.registerReceiver(br, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
}
public class CustomReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
String toastMessage = "TOAST";
switch (intentAction){
case Intent.ACTION_POWER_CONNECTED:
toastMessage="Power Connected!";
break;
case Intent.ACTION_POWER_DISCONNECTED:
toastMessage="Power Disconnected!";
break;
}
Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
}
}
When I go to onPause() and onStop() the app continues to show toast message of connect and disconnect charge. I don't know why.
My guess is that condition (which you're using in onPause() and onStop()) br.isOrderedBroadcast() is false so CustomReceiver won't get unregistered.
Also, according to the documentation, you should register/unregister CustomReceiver either in onCreate()/onDestroy() or in onResume()/onPause().
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);
}
myButton is a button that when clicked is supposed to receive a broadcast from a background IntentService. But the broadcast is never received. However if I move the broadcastReceiver outside of myButton.setOnClickListener function, then I begin to receive broadcasts from my background service.
Is there a way to make the broadcastReceiver receive broadcasts within the setOnClickListener function?
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
});
public void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter(SimpleIntentService.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver,filter);
}
public void onPause()
{
unregisterReceiver(broadcastReceiver);
super.onPause();
}
}
I had to take out the broadcastReceiver from onClick method. This works and broadcast is received:
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//do extra stuff
}
});
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
}
Do you forget to registerReceiver?
You might also need to assign a IntentFilter when you register a receiver.
The following is some sample codes from my project:
private class LocationInfoReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do something
}
}
locationInfoReceiver = new LocationInfoReceiver();
// the key you use setAction() method in your Intent Service
IntentFilter locationInfoReceiverFilter = new IntentFilter("your key");
locationInfoReceiverFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(locationInfoReceiver, locationInfoReceiverFilter);
I want to display an alert when a sms is received, so my idea is to start a new activity that launch the alertdialog.
My service starts with no problem, and starts receiver as well..
I can receive sms and display toast alerts fine.. but i'd like to show a custom alertdialog instead.
This is the activity that starts my service (ServiceExampleActivity ):
public class ServiceExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStartService = (Button) findViewById(R.id.btnStart);
Button btnStopService = (Button) findViewById(R.id.btnStop);
btnStartService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartMyService();
}
});
btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StopMyService();
}
});
}
private void StartMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
startService(myServiceIntent);
}
private void StopMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
stopService(myServiceIntent);
}
}
This is my Service (ServiceTest):
public class ServiceTest extends Service {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver myBroadcastReceiver = null;
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
StartDialogActivity(context, intent);
}
};
this.registerReceiver(myBroadcastReceiver, theFilter);
}
#Override
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("ServiceTest", "Started");
Toast.makeText(this, "Service started...", 3000).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
Toast.makeText(this, "Service destroyed...", 3000).show();
}
private void StartDialogActivity(Context context, Intent intent) {
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dlgIntent);
}
}
And this is the activity i want to launch to display the alertdialog normally..
public class DialogActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
}
When it tries to start the activity, the app crashes..
Can you tell me were is the error..??
Like this, you want start activity from service
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dlgIntent );
I want to start my Application (ex update my TextView) after press back button. But it didn't work. Please help me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
registerReceiver(intentReceiver, intentFilter);
}
protected void onPause() {
registerReceiver(intentReceiver, intentFilter);
super.onPause();
}
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
sendSMS("123","message");
}
};
I have updated your code try this and if any problem is there then ask me. I will try to help you ..
#Override
public void onBackPressed() {
// FOR UPDATING YOUR TEXT VIEW.
Intent broadcast_intent = new Intent("SMS_RECEIVED_ACTION");
broadcast_intent.putExtra("number", textview_value_to_set);
sendBroadcast(broadcast_intent);
// // FOR STARTING YOUR NEW ACTIVITY.
Intent intent = new Intent(getApplicationContext(), class_name.class);
startActivity(intent);
super.onBackPressed();
}
Use this as your broadcast receiver. Dont forget to register reciever.
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SMS_RECEIVED_ACTION")) {
TextView text = (TextView)findViewById(R.id.text);
text.setText(intent.getExtras().getString("number"));
}
}
};