I have an BroadcastReciver that listens for incoming sms. When sms come, it shows notification. I want, when user open notification, it's go to result activity, and it's open google map via intent.
I think I wrote everything ok, but it doesn't work. When the notification is clicked, it opens a blank page.
My incomingSms BroadcastReciver :
public void ShowNotif(String from , String body , Context con){
NotificationCompat.Builder builder =
new NotificationCompat.Builder(con)
.setSmallIcon(R.drawable.ic_search)
.setContentTitle(from)
.setContentText(body);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(con,Resualt.class );
targetIntent.putExtra("loc",body);
PendingIntent contentIntent = PendingIntent.getActivity(con, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) con.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
Intent goResIntent = new Intent(con , Resualt.class);
con.startActivity(goResIntent);
// gogole map intent :
}
and Resualt acitivty :
public class Resualt extends Activity {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.resualt);
double Mylatitude = 12;
double Mylongitude = 11;
GPSTracker tracker = new GPSTracker(this);
if (tracker.canGetLocation()) {
Mylatitude = tracker.getLatitude();
Mylongitude = tracker.getLongitude();
}
Intent intent = getIntent();
String location = intent.getStringExtra("loc");
String ACC_lat = location.substring(0, location.indexOf(","));
String ACC_lang = location.substring(location.indexOf(",") + 1, location.length());
Toast.makeText(this, ACC_lang + " ^ " + ACC_lat, Toast.LENGTH_LONG).show();
Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+Mylatitude +","+ Mylongitude+"&daddr="+ACC_lat+","+ACC_lang));
startActivity(mapIntent);
// this.finish();
}
thanks for any help .
You can open a single blank activity through pending intent in notification service and then on that blank activity open a map intent and finish that blank activity.
the link receiving from notification data can be sent through intent as extras
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("location_link", link);
Related
I want to update the content for a reminder after it has been added before being received by the user. After setting a reminder through AlarmManager using the data stored in sqlite database, the notification from the reminder set only shows the data, title and description, that was first added, not any updated data stored corresponding to the ID as primary key.
Things I have tried:
cancelling the pending intent for the reminder then setting it again after updating the data stored in the database but it still displays the same result.
using an activity for adding data to be stored in the database to set a reminder and using another activity for updating this data as an attempt to update the reminder content with the same ID issued. One result shows two notifications received, one with initial title and description, and the other with updated information.
Currently, the methods I use to set and cancel a reminder is in my Adapter class for Recyclerview. I am stuck on updating although adding and cancel works fine.
Update: Now I use two separate activities for the add and update reminder functions.
For adding a reminder:
databaseManager.addReminder(titlePicked, descriptionPicked, timePicked, datePicked, dateTimePicked);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
setAlarm();
private void setAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
intent.putExtra("DateTime", dateTimePicked);
intent.putExtra("NotifID", remId);
intent.putExtra("Title", titlePicked);
intent.putExtra("Description", descriptionPicked);
PendingIntent addIntent = PendingIntent.getBroadcast(this, remId, intent, 0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), addIntent);
}
For updating a reminder:
databaseManager.updateReminder(remindId, titlePicked2, descriptionPicked2, timePicked, datePicked, dateTimePicked);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
updateAlarm();
private void updateAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
intent.putExtra("DateTime", dateTimePicked);
intent.putExtra("NotifID", remindId);
intent.putExtra("Title", titlePicked2);
intent.putExtra("Description", descriptionPicked2);
PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent, 0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), updateIntent);
}
Receiver class:
public class ReminderReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "CHANNEL_REMIND";
String DateTimeChoice, TitleChoice, DescriptionChoice;
int notificationID;
#Override
public void onReceive(Context context, Intent intent) {
DateTimeChoice = intent.getStringExtra("DateTime");
notificationID = intent.getIntExtra("NotifID", 0);
TitleChoice = intent.getStringExtra("Title");
DescriptionChoice = intent.getStringExtra("Description");
Intent mainIntent = new Intent(context, ViewReminder.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, notificationID, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// For API 26 and above
CharSequence channelName = "My Notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(TitleChoice)
.setContentText(DescriptionChoice)
.setContentIntent(contentIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(context.getResources().getColor(R.color.purple_700))
.setAutoCancel(true);
notificationManager.notify(notificationID, builder.build());
}
Adapter class:
int remindId = reminder.getReminderId();
databaseManager = new DatabaseManager(holder.view.getContext());
sqLiteDB = databaseManager.getWritableDatabase();
public void onClick(View view) {
Reminder reminder = remindList.get(holder.getAdapterPosition());
PopupMenu popupMenu = new PopupMenu(view.getContext(), view);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add("Edit").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Intent intent = new Intent(view.getContext(), UpdateReminderActivity.class);
intent.putExtra("reminderId", remindId);
intent.putExtra("title", reminder.getReminderTitle());
intent.putExtra("definition", reminder.getReminderDefinition());
view.getContext().startActivity(intent);
return true;
}
});
For updating a pending intent, you need to use FlAG_UPDATE_CURRENT with the same id you used earlier to set the initial intent.
If you want to update the alarm associated with that pending intent, you need to cancel the old alarm & then the old PendingIntent. Then create a new PendingIntent like this,
PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent,PendingIntent.FLAG_UPDATE_CURRENT);
and set it to the alarm.
I would like to display the status of notification depending on order status changes. As of now, i am able to display it. Now the next task is that when user clicks on notification, I prefer to take this to the track order fragment where the user can see his order status in detail.
Here is my code:
public static void createNotification(FragmentActivity activity, boolean isLoggedIn, String selectedOrderId, String order_status, String status_desc)
{
NotificationCompat.Builder builder =
new NotificationCompat.Builder(activity)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Lugmah Order Status")
.setContentText("The Order Status of Order Id: "+selectedOrderId+ "is: "+status_desc)
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setAutoCancel(true);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(activity, TrackOrderFragment.class);
targetIntent.putExtra("isTrackOrder", false);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
if(isLoggedIn)
{
if(status_desc.equals("Rejected"))
{
targetIntent.putExtra("isLoggedIn", true);
targetIntent.putExtra("status_desc", status_desc);
fragment.setArguments(bundle);
bundle.putString("status_desc", status_desc);
bundle.putString("selectedOrderId", selectedOrderId);
targetIntent.putExtras(bundle);
stackBuilder.addParentStack(TrackOrderFragment.class);
stackBuilder.addNextIntent(targetIntent);
}
}
else
{
targetIntent.putExtra("isLoggedIn", false);
}
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
//PendingIntent contentIntent = PendingIntent.getActivity(activity, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
}
And I would like to pass the data that is Status_desc and SelectedOrderId between two fragments.
To receive data, here is the code I wrote.
status_desc = getArguments().getString("status_desc");
rejectedOrderId = getArguments().getString("rejectedOrderId");
Here the I am getting notification when admin changes order status. But, I am not able to navigate to TrackOrderFragment.class onClick of Notification.
Help would be appreciated.
You can try the below code on button click
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
May be doing
Intent targetIntent = new Intent(activity, TrackOrderActivity.class); instead of Intent targetIntent = new Intent(activity, TrackOrderFragment.class); would help you. You may send a flag as intent extra to know whether the activity is created from notification. Attach the fragment with that activity.
I was mainly talking about this code block.
NotificationCompat.Builder builder =
new NotificationCompat.Builder(activity)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Lugmah Order Status")
.setContentText("The Order Status of Order Id: "+selectedOrderId+ "is: "+status_desc)
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setAutoCancel(true);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(activity, TrackOrderActivity.class);
targetIntent.putExtra("isTrackOrder", false);
Bundle bundle = new Bundle();
if(isLoggedIn)
{
if(status_desc.equals("Rejected"))
{
targetIntent.putExtra("isFromNotification", true);
bundle.putString("status_desc", status_desc);
bundle.putString("sejectedOrderId", selectedOrderId);
targetIntent.putExtra("orderBundle",bundle);
}
}
else
{
targetIntent.putExtra("isLoggedIn", false);
}
//PendingIntent
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
targetIntent, 0);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
Now inside of the TrackOrderActivity onCreate method do this.
setContentView(R.layout.activity_track_order);
if(getIntent().getBooleanExtra("isFromNotification",true)){
TrackOrderFragment fragment = new TrackOrderFragment();
fragment.setArguments(getIntent().getBundleExtra("orderBundle"));
getSupportFragmentManager().beginTransaction().
replace(R.id.container,fragment).commit();
}
Now on your TrackOrderFragment if you call getArguments() I think you will get your bundle data.
I have wired up a notifications action handler with PendingIntent.getBroadcast that shows actions inside the notification. The actions work fine, when I use the default click event on the heads up notification it works fine. My issue comes when the notification is in the tray and I have other notifications in the drawer, I am trying to program the default click/touch event on the notification to broadcast to the receiver and run an action. Here is some code:
Uri alertSound = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/page_the_doctor");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.telemed_logo)
.setContentTitle("PATIENT READY")
.setContentText(notification)
.setDefaults( Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setSound( alertSound )
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
//CLICK ON NOTIFICATION HERE ONLY WORKS ON HEADS UP AND NOT DEFAULT
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class);
notificationIntent.putExtra("visitId", visitId);
notificationIntent.putExtra("link", link);
notificationIntent.setAction(ACCEPT_EXAM);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(clickIntent);
//Accept intent action works fine
Intent acceptExam = new Intent(ctx, PushNotificationActions.class);
acceptExam.setAction(ACCEPT_EXAM);
acceptExam.putExtra("visitId", visitId);
acceptExam.putExtra("link", link);
PendingIntent pendingAcceptIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), acceptExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.accept_action_24dp, "ACCEPT", pendingAcceptIntent);
//Dismiss intent action works fine
Intent dismissExam = new Intent(ctx, PushNotificationActions.class);
dismissExam.setAction(DISMISS_EXAM);
dismissExam.putExtra("visitId", visitId);
dismissExam.putExtra("link", link);
PendingIntent pendingDismissIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), dismissExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.dismiss_action_24dp, "DISMISS", pendingDismissIntent);
Notification noti = notificationBuilder.build();
noti.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(visitId), noti);
Here is the onReceive method:
private Context context;
#Override
public void onReceive(Context ctx, final Intent intent) {
Log.d("PushNotificationActions","Started");
String action = intent.getAction();
Log.d("<-------------------<<<", "getaction is: " + action);
context = ctx;
if (ACCEPT_EXAM.equals(action)) {
Log.d("ACCEPT_ACTION", "READY FOR EXAM NOW");
Map<String, String> params = new HashMap();
params.put("email", email);
final JSONObject parameters = new JSONObject(params);
Log.d("parameters: ", parameters.toString());
volleyJsonObjectPost("ws", parameters, new Login.ServerCallback() {
public void onSuccess(JSONObject response) {
try {
final JSONObject loginData = response.getJSONObject("d");
DataModel.sharedInstance().key = loginData.getString("key");
final String visitLink; String link; final String visitId; Bundle extras = intent.getExtras();
if(extras != null) {
link = extras.getString("link");
visitId = extras.getString("visitId");
visitLink = link + loginData.getString("key") + ',' + visitId;
JSONObject params = new JSONObject();
params.put("key", loginData.getString("key"));
Log.d("params: ", params.toString());
volleyJsonObjectPost("ws", params, new Login.ServerCallback() {
public void onSuccess(JSONObject result) {
try {
final JSONObject acceptExamResultData = result.getJSONObject("d");
Log.d("acceptExamResultData: ", acceptExamResultData.toString());
if (acceptExamResultData.getBoolean("status") == true) {
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(visitLink));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.android.chrome");
try {
context.startActivity(intent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(visitId));
} catch (ActivityNotFoundException ex) {
// Chrome browser presumably not installed so allow user to choose instead
intent.setPackage(null);
context.startActivity(intent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(visitId));
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
}else {
// Exam was already accepted by another Doc
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}else if (DISMISS_EXAM.equals(action)) {
Log.d("DISMISS_ACTION", "I CANNOT TAKE THIS EXAM");
String visitId; Bundle extras = intent.getExtras();
if(extras != null) {
visitId = extras.getString("visitId");
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("Visit ID to cancel", visitId);
mNotificationManager.cancel(Integer.parseInt(visitId));
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
}
Here is the receiver in the manifest:
<receiver android:name=".PushNotificationActions" >
<intent-filter>
<action android:name="com.Telemed.app.ACCEPT_EXAM" />
<action android:name="com.Telemed.app.DISMISS_EXAM" />
</intent-filter>
</receiver>
Since the notification won't slide easy in the drawer in most cases I need this default functionality to mirror the Accept Exam Action. Only I don't want it to be an action, I just want it to work when the user clicks on the notification. I need to use getBroadcast because I am making a web service call (async) to get some data I need to do the next step
So in order to set the default functionality for the notification you have to create a default pending intent before constructing your notification builder:
Like so:
//CLICK ON NOTIFICATION
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Now after that set this:
.setContentIntent(clickIntent)
in the new NotificationCompat.Builder. After that you can set up as many actions as you want but the default will still access your action and act as a default in the case where the drawer sticks your notification at the to and you cannot see your programmed actions.
Uri alertSound = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/page_the_doctor");
//CLICK ON NOTIFICATION
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.telemed_logo)
.setContentTitle("TELEMED PATIENT READY")
.setContentText(notification)
.setDefaults( Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setSound( alertSound )
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(clickIntent)
.setAutoCancel(true);
//Accept intent
Intent acceptExam = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent pendingAcceptIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), acceptExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.accept_action_24dp, "ACCEPT", pendingAcceptIntent);
//Dismiss intent
Intent dismissExam = new Intent(ctx, PushNotificationActions.class).setAction(DISMISS_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent pendingDismissIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), dismissExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.dismiss_action_24dp, "DISMISS", pendingDismissIntent);
Notification noti = notificationBuilder.build();
noti.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(visitId), noti);
I have an app which shows battery charge and temperature in the status bar and notification bar. When the app is opened I can see the data updates in the status bar and notification. When I exit/close the app the status bar and notification is not updating its values. Why is the status bar and notification bar not updating when I close the app?
I use BroadcastReceiver to display the notification.
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
notificationMessage(context, intent);
}
private void notificationMessage(Context context, Intent intent){
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
int icon = R.drawable.battery_level_images;
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
float cTemperature = (float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)/10;
float fTemperature = celsiusToFahrenheit(cTemperature);
float voltage = (float) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)/1000;
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
String healthText = getHealthText(health);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("" + level + "% | " + healthText)
.setContentText(cTemperature + "\u2103 | " + fTemperature + "\u2109 | " + voltage + "V")
.setSmallIcon(icon, level)
.setWhen(0)
.setProgress(100, level, false)
.setOngoing(true)
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(0, notification);
}
In my main activity class I turn on the notification with a checkbox.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
............................
myReceiver = new MyReceiver();
ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatus = this.registerReceiver(mBatteryInfoReceiver, ifilter);
....................
}
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((CheckBox) view).isChecked();
if (on) {
batteryStatus = this.registerReceiver(myReceiver, ifilter);
SavingData.setNotificationState(true);
} else {
try{
this.unregisterReceiver(myReceiver);
}catch (IllegalArgumentException iae){
iae.printStackTrace();
}
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
SavingData.setNotificationState(false);
}
}
Here is my BroadcastReceiver in my AndroidManifest.
<receiver android:name=".MyReceiver" />
Register your BroadcastReceiver in your service and run it in your background. Running your service all the time might drain users battery. Beware :)
Once your activity is destroyed, your BroadcastReceiver registered via registerReceiver() will go away as well. You probably have a warning or error in LogCat pointing this out to you. Once your BroadcastReceiver is gone, you will stop updating the Notification.
I would like to put two buttons on my notifications from the status bar. Of course they do not appear until the user touches to expand them. I have created the custom layout for my notification using RemoteViews but am unsure if it's possible to obtain a reference to them because of my current code structure.
#Override
public void onMessage(Context context, Intent intent) {
Log.w("C2DMReceiver",
"Message Received, this is the message with no payload");
Bundle extras = intent.getExtras();
if (extras != null) {
String[] payload = new String[3];
payload[0] = (String) extras.get("payload");
payload[1] = (String) extras.get("payload2");
SharedPreferences sharedP = Prefs.get(this);
boolean inApp = sharedP.getBoolean("currentlyInApp", true);
if (!inApp) {
createNotification(context, payload);
}
}
}
public void createNotification(Context context, String[] payload) {
SharedPreferences sharedP = Prefs.get(context);
boolean needsToLogin = sharedP
.getBoolean("loginFromNotification", true);
Log.w("C2DMReceiver", "createNotification called");
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, WebViewActivity.class);
Intent notificationIntent2 = new Intent(this, UniteActivity.class);
PendingIntent pIntent;
if (needsToLogin) {
pIntent = PendingIntent.getActivity(this, 0, notificationIntent2,
PendingIntent.FLAG_CANCEL_CURRENT);
} else {
pIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
// Compatibility builder
NotificationCompat.Builder notification = new NotificationCompat.Builder(
context);
RemoteViews remote = new RemoteViews(getPackageName(),R.layout.notification);
//Button okButton = (Button) findViewById(R.layout.notification);
notification.setAutoCancel(false);
notification.setContent(remote);
notification.setContentIntent(pIntent);
notification.setWhen(System.currentTimeMillis());
notification.setTicker(payload[0]);
notification.setSmallIcon(R.drawable.default1);
notification.setContentTitle(payload[1]);
notification.setContentText(payload[0]);
long duration[] = { 100, 300, 100 };
notification.setVibrate(duration);
notificationmanager.notify(0, notification.getNotification());
}
onMessage is a method pulled from the Google C2DM library where the notifications are generated by intents received from google. Without a view, how can I obtain a reference to my buttons using findViewById()? or some other means
I think you are looking for the method:
RemoteViews.setOnClickPendingIntent(int, android.app.PendingIntent)
So, if you add...
remote.setOnClickPendingIntent(R.id.button, pIntent);
...it should work.