AlertDialog from within BroadcastReceiver? Can it be done? I am working on a app that will pop up a Dialog box if I get SMS message. I am trying to code this within a BroadcaseReceiver. But I cant use this line of code AlertDialog.Builder builder = new AlertDialog.Builder(this);. Can someone please help me with a hint!
public class SMSPopUpReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
if (intent.getAction().equals(SMSPopUpReceiver.ACTION)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus){
SmsMessage messages =
SmsMessage.createFromPdu((byte[]) pdu);
sb.append("Received SMS\nFrom: ");
sb.append(messages.getDisplayOriginatingAddress());
sb.append("\n----Message----\n");
sb.append( messages.getDisplayMessageBody());
}
}
Log.i(SMSPopUpReceiver.LOG_TAG,
"[SMSApp] onReceiveIntent: " + sb);
Toast.makeText
(context, sb.toString(), Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
}
}
Principal issue: try to avoid placing time consuming functionalities into BroadcastReceiver. It should just receive and initiate further processing in bound Activity/Service.
UPDATE:
Please check following sources that might be helpful:
Similar questions on StackOverflow:
How to send data from BroadcastReceiver to an Activity in android?
Android SMS receiver not working
Android SDK demo example:
android-sdk-windows\samples\android-8\ApiDemos\src\com\example\android\apis\os\SmsMessagingDemo.java
And of course standard Android API documentation: http://developer.android.com/reference/android/content/BroadcastReceiver.html
UPDATE2:
Added app skeleton as it should look. Please note that no content view is defined. It is because your app will have transparent screen. To achieve that
#android:style/Theme.Translucent
is entered under Theme tag for this activity in AndroidManifest.xml.
public class NotifySMSReceived extends Activity
{
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(mReceivedSMSReceiver, filter);
}
private void displayAlert()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setCancelable(
false).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action))
{
//your SMS processing code
displayAlert();
}
}
};
}
I've been looking into it and the documentation of the BroadcastReceiver actually says:
public abstract void onReceive
(Context context, Intent intent)
Since: API Level 1 This method is
called when the BroadcastReceiver is
receiving an Intent broadcast. During
this time you can use the other
methods on BroadcastReceiver to
view/modify the current result values.
The function is normally called within
the main thread of its process, so you
should never perform long-running
operations in it (there is a timeout
of 10 seconds that the system allows
before considering the receiver to be
blocked and a candidate to be killed).
You cannot launch a popup dialog in
your implementation of onReceive().
You cannot launch a popup dialog in
your implementation of onReceive()
So it seems it is not possible
This is late but this may help someone.
You cannot use alert dialog inside broadcast receiver, we can use this only in activity or service. Try like this
In your onReceive method of broadcastreceiver add
Intent i = new Intent(context, yourclass.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and in yourclass set your dialog message, so that it will appear when you trigger the receiver event. I tried this and it worked me. Hope this may help some one :-)
you can create a new transparent activity and then create Alert Dialog in that activity, whenever your alert is to be displayed call that activity from your broadcast reciever ,this could work, not tested
replace the word "this" inside the AlertDilaog with "context" -- the first parameter on you onRecieve method.
public void onReceive(Context context, Intent intent)
Related
Edit with an update at the bottom with the cause, but still no fix
I am trying to capture a notification and later replay it once I dismiss it. From what I've been able to figure out so far, I can capture a notification, but when I try create a new notification using NotificationManager.notify(), nothing happens. No errors, nothing. Is this even something I should be able to do?
Maybe I am not taking the right approach and someone can suggest a better approach. Like I stated above, I want to be able to know when a user receives a notification and to capture the notification in its entirety, so even when it's dismissed, I can restore it. Maybe there is a way to restore things from the notification history but I haven't been able to figure out fully how that works yet. Here's the code I have so far. I can successfully listen to when a notification is posted or removed. The goal is to send a broadcast when a notification is posted with the notification id and the actual Notification itself (this part works I think), and when the button is pressed, recreate the notification. When I press the button, nothing happens.
public class MainActivity extends AppCompatActivity {
private int notification_id = -1;
private Notification myNotify;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle extras = myNotify.extras;
String title = extras.getString("android.title");
String text = extras.getString("android.text");
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nManager.notify(notification_id, myNotify);
}
});
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("notification_restore");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
#Nullable
public void onReceive(Context context, Intent intent) {
// Here you have the received broadcast
// And if you added extras to the intent get them here too
// this needs some null checks
Bundle b = intent.getExtras();
notification_id = b.getInt("notification_id");
myNotify = b.getParcelable("notification");
}
}
}
public class MyNotificationListenerService extends NotificationListenerService {
private int notification_id;
private Notification myNotify;
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
//Ignore the notification
return;
}
notification_id = sbn.getId();
myNotify = sbn.getNotification();
Intent intent = new Intent("notification_restore");
Bundle b = new Bundle();
b.putInt("notification_id", notification_id);
b.putParcelable("notification", myNotify);
intent.putExtras(b);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
//Ignore the notification
return;
}
}
}
Edit:
So it looks like the reason my notification isn't showing up is because it complains about not finding a channel, even though the notification I am trying to replay has one. The exact error is:
E/NotificationService: No Channel found for pkg=com.gevdev.notify, channelId=bugle_default_channel, id=0, tag=null, opPkg=com.gevdev.notify, callingUid=10086, userId=0, incomingUserId=0, notificationUid=10086, notification=Notification(channel=bugle_default_channel pri=1 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x10 color=0xff2a56c6 category=msg groupKey=bugle_notification_group_key sortKey=00 actions=2 vis=PRIVATE)
I am still new to android, but my initial guess is that the channelId found bugle_default_channel isn't found under my package name, but I don't know how to fix this yet.
Figured it out
Even though the notification that I am grabbing to replay has a channel ID, the NotificationManager doesn't have that notification channel registered. I figured it based off the code found here. This is how to register it.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = nManager.getNotificationChannel(myNotify.getChannelId());
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(myNotify.getChannelId(), "Description Goes Here", importance);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(true);
nManager.createNotificationChannel(notificationChannel);\
}
}
I have this app which parses SMS and then converts them into Audio. My app users usually minimize the app and runs it all the time. But my app is getting terminated after sometime. How can i make sure my app will run till a user "terminates" it. Since the core functionality of the app is to convert SMS to audio, i need it running all the time.How can i do this ?
My current MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txtGateway, txtTime, txtAmount;
Speakerbox speakerbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textView = findViewById(R.id.txt_message);
speakerbox = new Speakerbox(getApplication());
txtAmount = findViewById(R.id.tv_amount);
txtGateway = findViewById(R.id.tv_gateway);
txtTime = findViewById(R.id.tv_time);
requestSmsPermission();
}
#Override
public void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onResume();
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onPause();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("otp")) {
final String message = intent.getStringExtra("message");
String gateway = intent.getStringExtra("gateway");
String time = intent.getStringExtra("time");
String amount = intent.getStringExtra("amount");
speakerbox.play(message);
txtGateway.setText(gateway);
txtTime.setText(time);
txtAmount.setText(amount);
// message is the fetching OTP
}
}
};
/**
* Requesting multiple permissions (storage and location) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestSmsPermission() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.SEND_SMS,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
// Toast.makeText(getApplicationContext(), "All permissions are granted!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
}
Use a foreground service to ensure that your app is not killed by Android. On newer version of Android, app's background process gets killed after sometime. Having a foreground service will ensure that your app stays active. Keep the service on background thread and not on the main thread.
Read more at:
https://developer.android.com/guide/components/services
and
https://androidwave.com/foreground-service-android-example/
Activities are used for user facing parts of your application. Use service instead. Most likely, your application is getting terminated by os due to low memory situation.
Use service for the core functionality if you want to run all the time in background.If user is not using your app actively yet app is taking RAM memory then OS will terminate the app to avoid out of memory.
I have a code for network change state in android. but now problem is that code shows the snack-bar when network state changed. i want that it will show dialogue box when network state get changed. I already done everything. i just want instead of snack-bar dialogue will be shown.
IntentFilter intentFilter = new IntentFilter(NetworkStateChangedReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
Snackbar.make(findViewById(R.id.activity_dashboard), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
}
}, intentFilter);
Just use the AlertDialog.Builder to create an alert dialog instead of Snackbar. Something along the following lines should work,
IntentFilter intentFilter = new IntentFilter(NetworkStateChangedReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
//Snackbar.make(findViewById(R.id.activity_dashboard), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
AlertDialog dialog = builder.create();
}
}, intentFilter);
This is a simple AlertDialog that you can use:
public static Dialog createSimpleOkDialog(Context context, String title, String message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setNegativeButton(android.R.string.ok, null);
return alertDialog.create();
}
I have a notepad activity that opens up a window dialog version of it where user can go to another app and still type on the notepad
For both notepad to have the same content, I used broadcastReceiver to set the text of the notepad activity to the one in the dialog when the user is done.
Activity's BroadcastReceiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
et_editor.setText(globalVariable.getScriptEditorText());
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Close Button of the Dialog:
btn_Close = (Button) view.findViewById(R.id.button_Close);
btn_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("Would you like to update the editor?")
.setNegativeButton("No, discard the changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ColorCoordinatePickerService.this, "Changes have been discarded", Toast.LENGTH_SHORT).show();
dialog.dismiss();
stopSelf();
}
})
.setPositiveButton("Yes, update with changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
})
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
});
It works BUT the user have to go back to the notepad activity (cannot be in another app or activity).
How do I update the notepad's content without having to "open" it up?
Queue the changes in BroadcastReceiver and when NotepadActivity resumes set the changes in the EditText. The queue doesn't need to be an actual queue, you can persist the last broadcast receiver data somewhere.
I am not sure, but it may be clear your global variable on moving from activity to another activity, also you are declaring the instance of global variable so it will set value in instance not in main variable and therefor you will not get it on receiver.
So I think you should set value in intent and then get it on receiver and manage it so it will work.
Check below, first your click event of dialog box method
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra("global_variable","" + CCEditor.getText().toString());
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
And now get value in receiver as like below.
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
String strData = intent.getExtras().getString("global_variable");
et_editor.setText(strData);
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Hope this will work
without opening acitivity,you want to update data then only one way you can do it.when you receive in receiver set all data into sharepreference.Whenever your notepad activity opens you can set take data from sharepreference and set it into notepad activity.
Use LocalBroadcastManager.
Example: How to use it
I need to close the current activity from a broadcast receiver. I'm not sure how to call finish from it, maybe there is a way to simulate a "Back" key keypress. Any implementation will be fine as long as it does the job.
#Override
public void onReceive(Context context, Intent intent) {
// How can I finish the current activity here?
}
At your broadcast receiver write:
YourCurrentActivityName.this.finish();
Or you can terminate the front activity with this.finish(); so the last open in stuck comes to front.
Update:
Code for first case:
Use of broadcast receiver to terminate activity at back stack:
public class ActivityFirstName extends Activity {
private BroadcastReceiver mFinishReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// other code
if (mFinishReceiver == null) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.ACTION_TERMINATE");// a string to identify your action
mFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// How can I finish the current activity here?
if ("com.example.ACTION_TERMINATE".equals(intent.getAction())) {
ActivityFirstName.this.finish();
}
}
};
registerReceiver(mFinishReceiver, intentFilter);
}
// other code
}
#Override
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
if (mFinishReceiver != null) {
unregisterReceiver(mFinishReceiver);
}
}
}
}
And the front/current running activity, the sender of the broadcast:
public class ActivitySecondName extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// code code code
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform action on click
terminateBackActivities();
}
});
}
private void terminateBackActivities() {
Intent i = new Intent("com.example.ACTION_TERMINATE"); // the two action strings MUST be same
// i.putExtra(...); // to send extra data
sendBroadcast(i);
}
}
You can simply call this.finish();
Assuming from your comment that the BroadcastReceiver is not an internal class of the activity, here is what you should do: Rather than having the broadcast receiver in a separate class, define it inside your activity like so:
private BroadcastReceiver mFinishReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
YourActivity.this.finish();
}
};
Then, you will want to register the receiver in onResume() as such:
#Override
public void onResume(){
super.onResume();
registerReceiver(mFinishReceiver, new IntentFilter(yourIntentAction));
}
You will also want to unregister this receiver in onPause() so you don't leak it:
#Override
public void onPause(){
super.onPause();
unregisterReceiver(mFinishReceiver);
}
Then you can remove the other receiver that had its own separate class and also remove its definition in the manifest. The above example will ensure that you can always call finish() with no issues because the receiver is only registered when the activity is running, as it is internal to the activity's class.
EDIT: Change the methods to onCreate() and onDestroy() rather than onPause() and onDestroy(), according to madlymad's comment.
The ActivityManager class can give you the current foreground activity (even if it's not from your app). The getRunningTasks methods will give you a list of the running tasks, the first element of the list being the most recent launched activity.Unfortunately,this method will just give you an object of type RecentTaskInfo , not the activity itself, so there is no way to call its finish() method,I believe :/
On the other hand, if you want to close the current activity from your app, you can implement a static variable on a personal class that each activiy would set in their onResume() method. This way you will always know what activity is the current one. But I guess it's not what you are looking for.
Edit: The getRunningTasks is just intended for debug purposes, as says the doc..
As suggested by other answers you can simply call finish() on the activity in the broadcast receiver code or you can even trigger a back button press key event yourself.
this.dispatchKeyEvent(new Keyevent(ACTION_DOWN, KEYCODE_BACK));
Not sure about whether this is helpfull to you or not but its help me once and i think thats a same case here so i am answering for you.
Whenever the broadcast receiver get call, you can navigate to any activity by clicking on that broadcast message.
Just like:
#Override
public void onReceive(Context context, Intent intent) {
// My Notification Code
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.app_icon;
//System.out.println("The ID Number is: "+Long.parseLong(intent.getData().getSchemeSpecificPart()) );
contentText = intent.getStringExtra("MyMessage");
System.out.println("The Message is: "+intent.getStringExtra("MyMessage"));
CharSequence text = "Your tax amount due period";
CharSequence contentTitle = "Tax Toolbox";
long when = System.currentTimeMillis();
intent = new Intent(context, MenuPageActivity.class); // here i am calling activity
intent.putExtra("sixMonth", "sixMonth");
intent.putExtra("messageSixMonth", contentText);
PendingIntent contentIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new Notification(icon,text,when);
long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate; // To vibrate the Device
notification.ledARGB = Color.RED;
notification.ledOffMS = 300;
notification.ledOnMS = 300;
notification.defaults |= Notification.DEFAULT_LIGHTS;
//notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(com.project.TaxToolbox.NotificationConstants.NOTIFICATION_ID_SIX_MONTH, notification);
}
Now, on the onCreate() of that activity you have to identify whether it is call by Notification or not.
As like:
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println("The Extra for twoMonth is: "+getIntent().hasExtra("twoMonth"));
System.out.println("The Extra for sixMonth is: "+getIntent().hasExtra("sixMonth"));
System.out.println("The Extra for EveryMonth is: "+getIntent().hasExtra("everyMonth"));
if(getIntent().hasExtra("sixMonth")){
notificationManager.cancel(NotificationConstants.NOTIFICATION_ID_SIX_MONTH);
final AlertDialog alert3 = new AlertDialog.Builder(MenuPageActivity.this).create();
alert3.setTitle("Tax Toolbox");
alert3.setMessage(getIntent().getExtras().getString("messageSixMonth"));
alert3.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alert3.setIcon(R.drawable.app_icon);
alert3.show();
// here you can do anything more or close the activity.
}
Not sure but might be helpfull to you.
Feel free to comments if it help you.
Create a common Activity class and extend this common class from all activities, that way you can have a centralized code. Have a register the broadcast receiver in onStart of the activity and unregister in onStop that way only one activity, the one which is visible will be registered for the broadcast intent.
Sample code:
public class BaseActivity extends Activity {
/*
* (non-Javadoc)
*
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(receiver, new IntentFilter(YOUR_INTENT_FILTER));
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStop()
*/
protected void onStop(){
unregisterReceiver(receiver);
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStart()
*/
protected void onStart(){
super.onStart();
registerReceiver(receiver, new IntentFilter(YOUR_INTENT_FILTER));
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
/*
* (non-Javadoc)
*
* #see
* android.content.BroadcastReceiver#onReceive(android.content.Context,
* android.content.Intent)
*/
#Override
public void onReceive(Context context, Intent intent) {
onBackPressed();//on back pressed simply calls finish()
}
};
} // End of BaseActivity
// End of File
Try using:
Intent i = new Intent(context,intent.getClass());
Follow the instructions from gezdy on How to get current foreground activity context in android? to ensure you can get a reference to the current activity from anywhere in your application.
From there you can call .finish() to close the current activity.
Place finish(); after u completed all the tasks in onReceive() of BroadcastReceiver class as below:
#Override
public void onReceive(Context context, Intent intent) {
// Do all the tasks onReceive of BroadCast Receiver
finish(); // This finishes the current activity here....
}