When user kill app,my service is running in the background.
It has a button which I can return to the map activity.However,when the user return to the app through the notification button after destroying the app,the map created but the information I am transfering from my service to my map activity is null.
When the user isn't killing the app and return through the notification button,the data exist.
This is my code:
//Map Activity
//OnPause = transfer the data to service intent(Working fine)
BackgroundLocation backgroundLocation = new BackgroundLocation();
mServiceIntent = new Intent(this, backgroundLocation.getClass());
if (!isMyServiceRunning(backgroundLocation.getClass())) {
mServiceIntent.putExtra("AddressBackgound",mAddress);
mServiceIntent.putExtra("AddressLatBackgound",destinationLat);
mServiceIntent.putExtra("AddressLngBackgound",destinationLng);
startService(mServiceIntent);
}
// OnMapReady = Getting the data from service intent(return null for all data)
if (myLocation != null) {
BackgroundLocation backgroundLocation = new BackgroundLocation();
mServiceIntent = new Intent(this, backgroundLocation.getClass());
Bundle extras = getIntent().getExtras();
if (isMyServiceRunning(backgroundLocation.getClass()) && extras != null) {
String mAddress2 = extras.getString("AddressBackgound22");
Double destinationLat2 = extras.getDouble("AddressLatBackgound22");
Double destinationLng2 = extras.getDouble("AddressLngBackgound22");
Log.e("onResume", "onResume stats");
Log.e("Address", "" + mAddress2);
Log.e("Lat", String.valueOf(destinationLat2));
Log.e("Lng", String.valueOf(destinationLng2));
Log.e("OnMapReady","Service is running....");
}
else{
Log.e("OnMapReady","Service is not running");
}
}
Background Location(Service Intent) = Getting information from MapsActivity and returnthe information to MapsActivity aswell.
//Service Intent
// OnStartCommand
Bundle extras = intent.getExtras();
if (extras != null) {
//getting the data to the service is working fine even when the app killed the service still working with the data.
mAddress = extras.getString("AddressBackgound");
destinationLat = extras.getDouble("AddressLatBackgound");
destinationLng = extras.getDouble("AddressLngBackgound");
//This is what I am trying to send to MapsActivity:
extras.putString("AddressBackgound22",mAddress);
extras.putDouble("AddressLatBackgound22",destinationLat);
extras.putDouble("AddressLngBackgound22",destinationLng);
Log.e("onStartCommand", "onStartCommand started");
Log.e("Address","" + mAddress);
Log.e("Lat", "" + destinationLat);
Log.e("Lng", "" + destinationLng);
}
Thank you for your time.
There is a many way,I say some of that:
1-Use store data in service (such as SharedPrefrences,DB and ...) and retrive in activity
2-Use eventbus or broadcast receivers
3-Use callback patern for callback data from service to activiy
So thanks to #Mohammadreza I used sharedPref on the service intent and its worked.
This is what I did:
public static final String MY_PREFS_NAME = "MyData";
//Save SharedPref(BackgroundActivity):
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("AddressBackgound",mAddress);
editor.putString("AddressLatBackgound", String.valueOf(destinationLat));
editor.putString("AddressLngBackgound", String.valueOf(destinationLng));
editor.apply();
//Read SharedPref(MapsActivity):
SharedPreferences prefs = getSharedPreferences(BackgroundLocation.MY_PREFS_NAME, MODE_PRIVATE);
BackgroundLocation backgroundLocation = new BackgroundLocation();
if (isMyServiceRunning(backgroundLocation.getClass()) && prefs != null ) {
String mAddress = prefs.getString("AddressBackgound","mAddress");
Double UserStartLocationLat = Double.parseDouble(String.valueOf(Double.valueOf(prefs.getString("UserStartLocationLat", "UserStartLocationLatNull"))));
Double UserStartLocationLng = Double.parseDouble(String.valueOf(Double.valueOf(prefs.getString("UserStartLocationLng", "UserStartLocationLngNull"))));
}
isMyServiceRunning:
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Service status", "Running");
return true;
}
}
Log.i ("Service status", "Not running");
return false;
}
you can use eventbus or broadcast receivers to send data from service to Activity/Fragment
Related
I'm receiving notifications using OneSignal, if my app was in the background, and I click on the came notification, the app opening normally as I wanted going to the requested activity without any problem!
But if the app was not running i mean totally closed, after tapping the notification nothing happening at all! app not opening! notification going away without opening the app! any advice?
Here is the code i'm using to handle OneSignal notifications
private class NotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String launchUrl = result.notification.payload.launchURL; // update docs launchUrl
String body = result.notification.payload.body; // update docs launchUrl
String customKey;
String openURL = null;
Object activityToLaunch = MainActivity.class;
if (data != null) {
customKey = data.optString("customkey", null);
openURL = data.optString("openURL", null);
if (customKey != null)
Log.i("OneSignalExample", "customkey set with value: " + customKey);
if (openURL != null)
Log.i("OneSignalExample", "openURL to webview with URL value: " + openURL);
}
if (actionType == OSNotificationAction.ActionType.ActionTaken) {
Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);
if (result.action.actionID.equals("id1")) {
Log.i("OneSignalExample", "button id called: " + result.action.actionID);
activityToLaunch = Notifications.class;
} else
Log.i("OneSignalExample", "button id called: " + result.action.actionID);
}
// The following can be used to open an Activity of your choice.
Intent toActivity = new Intent(MainActivity.this, Notifications.class);
toActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
toActivity.putExtra("openURL", launchUrl);
toActivity.putExtra("body", body);
Log.i("OneSignalExample", "openURL = " + launchUrl);
//my Code
String message;
SharedPreferences sharedPreferences = getSharedPreferences(NOTES, Context
.MODE_PRIVATE);
String jsonLink = sharedPreferences.getString(NOTES_LINKS, null);
String jsonTitle = sharedPreferences.getString(NOTES_TITLE, null);
if (jsonLink != null && jsonTitle != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
}.getType());
ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(launchUrl)) {
message = "Notification Exist!";
Log.i("Notifications","Notification Exist!");
} else {
linkList.add(launchUrl);
titleList.add(body.trim());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(NOTES_LINKS, new Gson().toJson(linkList));
editor.putString(NOTES_TITLE, new Gson().toJson(titleList));
editor.apply();
Log.i("Notifications","Notification Stored!");
}
} else {
ArrayList<String> linkList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
linkList.add(launchUrl);
titleList.add(body.trim());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(NOTES_LINKS, new Gson().toJson(linkList));
editor.putString(NOTES_TITLE, new Gson().toJson(titleList));
editor.apply();
Log.i("Notifications","Stored");
}
// startActivity(intent);
startActivity(toActivity);
}
}
I am just digging for another issue with onesignal notification, and found this question,
I would like to answer like:
what value have you set for NotificationOpened.DEFAULT in Manifest.
"Enable" will open your application.
<application> <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="Enable" /></application>
i was facing the same issue before and was able to solve it by creating an application class and initializing oneSignal in it
public class Application extends android.app.Application {
#Override
public void onCreate() {
super.onCreate();
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new NotificationHandler(this))
.init();
}
}
you also need to add these in your manifist
<application
android:name="Application"
...>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>
I am writing the a phone call function during the remote control.
It should be turn to my incoming call pages , but when i recieve a call , it will output "AudioTrack: releaseBuffer() track 0xb4d4db00 disabled due to previous underrun, restarting" . How can i fix it ??
The function can handle the call but can not change the pages.
Here is apart of code
public void onIncomingCall(VoiceCall call) {
PermissionUtils.unregisterDelegate(mRecordAudioDelegate);
mRemoteViewInitized = false;
mRemoteView.disconnect();
mRemoteView.setCallback(null);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
RemoteContact callerContact = call.getIncomingCallerContact();
Log.d(TAG,"failed");
activeCallId = call.getCallId();
if (callerContact != null) {
number =callerContact.getDisplayName() +" "+
callerContact.getFirstDisplayNumber();
}else{
number = call.getRemoteUserNumber();
}
// updateTextView(call);
mLoginClient = MbaClientApp.getInstance(MbaRemoteControlActivity.this).getLoginClient();
final LcLoginClient.LcService service =
mLoginClient.getService(PACKAGE_NAME_VOICE_CALL_SERVER);
if (service != null) {
Intent intent =
new Intent(MbaRemoteControlActivity.this, IncomingCall.class);
intent.putExtra(
IncomingCall.INTENT_KEY_INT_VOICE_CALL_PORT,
Integer.valueOf(service.get(LcLoginClient.LcService.Key.KEY_PORT)));
intent.putExtra(
IncomingCall.INTENT_KEY_INT_VOICE_CALL_HOST,
serverHost);
intent.putExtra("host", mHost);
intent.putExtra("call", activeCallId);
intent.putExtra("phone", number);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}
I have created a service which launch Activity after receiving SMS from certain numbers.
There are 2 Activities Success and Failure.
Both Activities opens successfully only 1 time, On second iteration, when i send SMS again, it does not effect Activity Screen.
It remains open the current Activity screen and does not change it based on the condition.
I searched this on net and found various solution, but nothing seems working here, I tried to change flags, but it only allows 1 flag from service class, and if i choose other Flags it gives me following error message.
StartActivity from outsite an activity context requires the FLAG_ACTIVITY_NEW_TASK flag
This is the service class i have written. Kindly check this and guide me what i am doing wrong here.
Thanks
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
int duration = Toast.LENGTH_LONG;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
if(senderNum.equals("345"))
{
Intent successScreen= new Intent(context, SuccessActivity.class);
successScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(successScreen);
}
else if(senderNum.equals("3450") || senderNum.equals("3451") || senderNum.equals("3452")){
Intent alertActivity = new Intent(context, FailureActivity.class);
alertActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alertActivity);
}
Try to replace your code with this code:
if(senderNum.equals("345"))
{
Intent successScreen= new Intent(context, SuccessActivity.class);
successScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
successScreen.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
successScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
context.startActivity(successScreen);
}
else if(senderNum.equals("3450") || senderNum.equals("3451") || senderNum.equals("3452")){
Intent alertActivity = new Intent(context, FailureActivity.class);
alertActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
successScreen.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
successScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
context.startActivity(alertActivity);
}
I have a mUsbReceiver (BroadcastReceiver) and CameraActivity. The receiver setContentView(R.layout.main) from CameraActivity via an Intent. Then CamearActivity updates its View with this value. Notice that the setContentView is in the Broadcast receiver class and not in the CameraActivity Class.
public class CameraActivity extends Activity {
private static final String TAG = "openXC::Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
usbConnection();
}
public void usbConnection() {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_CANCEL_CURRENT);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
String txt = "default";
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Log.i(TAG, "Device List: " + deviceList);
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next();
Log.i(TAG, "Device List: " + deviceList);
mUsbManager.requestPermission(device, mPermissionIntent);
}
private static final String ACTION_USB_PERMISSION ="com.ford.openxc.webcam.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
Log.d(TAG, "Displayed Comten View " + device);
setContentView(R.layout.main);
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
}
This works fine sometimes but sometimes throws the following error
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/Adreno200-EGLSUB( 5609): <ConfigWindowMatch:2087>: Format RGBA_8888.
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
D/openXC::Activity( 5609): Displayed Comten View UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421d3ed0]
D/WebcamPreview( 5609): WebcamPreview constructed
Technically, you can call setContentView any time you are executing on the event thread.
Otherwise you need to use a Handler to call it.
Also, here are some usefull links that might help you:
link1
link 2
link 3
I dont have much exp on USB sort of thing but since u said its saying cannot readfile.. i believe dat the error may be in the usb so for the debugging purpose i would suggest to move the setContentView(int) from if conditions to the onRecieve directly so dat whenever the onReceive is called ur contenview will change , this will help to ensure that the error is not with setcontentview... After dat u can see without setcontentview in the usb and now if the error is coming then surely the error is in the usb and not in the setContentView ....
Hope it works :)
In my Android app, I use the Mobile Backend Starter from Google. I'd like to get a notification when the CloudEntities on the server get updated, and this notification should contain some data from the updated Entity. It works when the app is running in the background, but when I close the app (by swiping it away in the multitasking view), I can't make such a notification because I haven't got access to the CloudBackendAsync in the GCMIntentService.
I already saw this question:
Mobile Backend handle continuous queries in background
But it doesn't have a solution for the problem of accessing the cloud data in the GCMIntentService.
EDIT: My current code in GCMIntentService.java
protected void onHandleIntent(Intent intent) {
//... (Check if the GCM Message is about an update of the Mobile Backend)
// dispatch message
if (GCM_TYPEID_QUERY.equals(typeId)) {
// Here, a broadcast is sent to the Main Activity of the app, which then downloads
// the new content and shows a notification in the CloudCallbackHandler. That
// only works when the Activity is running.
// So I would like to get access to the CloudBackendAsync instance from
// the app here to download data in the background and show a notification.
Intent messageIntent = new Intent(BROADCAST_ON_MESSAGE);
messageIntent.putExtras(intent);
messageIntent.putExtra("token", tokens[2]);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
//...
}
The Android client does not receive the message content through the push notification event from the backend (only the subId token is sent from the demo backend which is enough to notify the client that some new message has been received for the given topic and refresh it).
So as I understand, it is not possible to directly get the entity data within the client GCMIntentService.onHandleIntent() method unless we change the backend code. I have made the following changes in the backend class ProspectiveSearchServlet so that it includes as well the message content within the push notification:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Return if push notification is not enabled
if (!backendConfigManager.isPushEnabled()) {
log.info("ProspectiveSearchServlet: couldn't send push notification because it is disabled.");
return;
}
// dispatch GCM messages to each subscribers
String[] subIds = req.getParameterValues("id");
// Each subId has this format "<regId>:query:<clientSubId>"
for (String subId : subIds) {
String regId = SubscriptionUtility.extractRegId(subId);
if (isSubscriptionActive(regId)) {
Entity matchedEntity = ProspectiveSearchServiceFactory.getProspectiveSearchService().getDocument(req);
if(matchedEntity != null) {
log.info(String.format("ProspectiveSearchServlet: matchedEntity.toString: " + matchedEntity.toString()));
} else {
log.info(String.format("ProspectiveSearchServlet: matchedEntity is null."));
}
//Add the matchedEntity object.
sendPushNotification(regId, subId, matchedEntity);
} else {
SubscriptionUtility.clearSubscriptionAndDeviceEntity(Arrays.asList(regId));
}
}
}
private void sendPushNotification(String regId, String subId, Entity matchedEntity) throws IOException {
SubscriptionUtility.MobileType type = SubscriptionUtility.getMobileType(subId);
if (SubscriptionUtility.MobileType.ANDROID == type) {
sendGcmAlert(subId, regId, matchedEntity);
} else if (SubscriptionUtility.MobileType.IOS == type) {
sendIosAlert(subId, new String[] {regId}, matchedEntity);
}
}
private void sendGcmAlert(String subId, String regId, Entity matchedEntity)
throws IOException {
String gcmKey = backendConfigManager.getGcmKey();
boolean isGcmKeySet = !(gcmKey == null || gcmKey.trim().length() == 0);
// Only attempt to send GCM if GcmKey is available
if (isGcmKeySet) {
Sender sender = new Sender(gcmKey);
if(matchedEntity != null) {
Message message = new Message.Builder().addData(SubscriptionUtility.GCM_KEY_SUBID, subId)
//extra data.<key> elements can be added here
.addData("data.message", (String) matchedEntity.getProperty("message"))
.addData("data.updatedBy", (String) matchedEntity.getProperty("_updatedBy"))
.addData("data.owner", (String) matchedEntity.getProperty("_owner"))
.addData("data.kindName", (String) matchedEntity.getProperty("_kindName"))
.build();
Result r = sender.send(message, regId, GCM_SEND_RETRIES);
if (r.getMessageId() != null) {
log.info("ProspectiveSearchServlet: GCM sent: subId: " + subId);
} else {
log.warning("ProspectiveSearchServlet: GCM error for subId: " + subId +
", senderId: " + gcmKey + ", error: " + r.getErrorCodeName());
ArrayList<String> deviceIds = new ArrayList<String>();
deviceIds.add(regId);
SubscriptionUtility.clearSubscriptionAndDeviceEntity(deviceIds);
}
}
} else {
// Otherwise, just write a log entry
log.info(String.format("ProspectiveSearchServlet: GCM is not sent: GcmKey: %s ",
isGcmKeySet));
}
}
Now on the client side you can make the following changes in the GCMIntentService to display a proper push notification (with the message body and the user name):
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Log.i(Consts.TAG, "onHandleIntent: message error");
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
Log.i(Consts.TAG, "onHandleIntent: message deleted");
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
String subId = intent.getStringExtra(GCM_KEY_SUBID);
Log.i(Consts.TAG, "onHandleIntent: subId: " + subId);
String[] tokens = subId.split(":");
String typeId = tokens[1];
// dispatch message
if (GCM_TYPEID_QUERY.equals(typeId)) {
Intent messageIntent = new Intent(BROADCAST_ON_MESSAGE);
messageIntent.putExtras(intent);
messageIntent.putExtra("token", tokens[2]);
boolean isReceived = LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
//Check if the broadcast has been handled, if not show the notification.
if (!isReceived) {
Log.i(Consts.TAG, "A message has been recieved but no broadcast was handled.");
generateNotification(this, intent, tokens[2]);
} else {
Log.i(Consts.TAG, "A message has been recieved, broadcasted and handled.");
}
}
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
public static void generateNotification(Context context, Intent intent, String message) {
//Event keys
HashMap data = new HashMap();
for (String key : intent.getExtras().keySet()) {
Log.d(Consts.TAG, "Message key: " + key + " value: " + intent.getExtras().getString(key));
String eventKey = key.startsWith("data.") ? key.substring(5) : key;
data.put(eventKey, intent.getExtras().getString(key));
}
CharSequence contentTitle = (CharSequence) data.get("updatedBy");
if (contentTitle == null) contentTitle = "New Message";
CharSequence contentText = (CharSequence) data.get("message");
if (contentText == null) contentText = "";
CharSequence userId = (CharSequence) data.get("updatedBy");
Bitmap iconBitmap = getUserIcon(context, userId.toString());
if (iconBitmap == null) iconBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
// Creates an Intent for the Activity
Intent resultIntent = new Intent(context, GuestbookActivity.class);
// The stack builder object will contain an artificial back stack for the started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(IntroductionActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder mBuilder = new Notification.Builder(context);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(iconBitmap)
.setTicker(contentTitle + ": " + contentText)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.build();
///Get the notification ID, /it allows to update the notification later on.
int notifyID = 1;
String contentID = (String) data.get("id");
if(contentID != null) {
notifyID = Integer.parseInt(contentID);
}
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyID, notification);
}