How to show Notifications from AlarmReceiver even when device has been restarted in jetpack compose - android-jetpack-compose

I have an application in Jetpack Compose that notifies scheduled alarms set by the user and it works well; however, when the device is restarted, the alarm does not sound. For example, if the user sets the alarm to go off in two minutes, this works; however, if the device is restarted before the alarm is triggered, the alarm will not sound.
I have this method to save an alarm:
#RequiresApi(Build.VERSION_CODES.M)
#Composable
fun AddPage(navController: NavController, vm: TaskViewModel = viewModel()) {
val scope= rememberCoroutineScope()
val calendar=Calendar.getInstance().apply {
timeInMillis=System.currentTimeMillis()
}
val title = remember {
mutableStateOf("")
}
val description = remember {
mutableStateOf("")
}
val year= remember {
mutableStateOf(calendar.get(Calendar.YEAR))
}
val month= remember {
mutableStateOf(calendar.get(Calendar.MONTH)+1)
}
val day= remember {
mutableStateOf(calendar.get(Calendar.DAY_OF_MONTH))
}
val hour= remember {
mutableStateOf(calendar.get(Calendar.HOUR_OF_DAY))
}
val minutes= remember {
mutableStateOf(calendar.get(Calendar.MINUTE))
}
val showPopup= remember {
mutableStateOf(false)
}
val msg= remember {
mutableStateOf("")
}
val icon= remember {
mutableStateOf(Icons.Filled.Done)
}
if (showPopup.value){
PopupMessagePage(msg.value,400.dp,500.dp,showPopup.value,{
showPopup.value=false
},
icon.value)
}
val context = LocalContext.current
Column(
modifier = Modifier
.fillMaxSize()
.padding(top = 30.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Agregar Tarea",
style = NoteTheme.typography.h1
)
RowOfThis(title, "Título", true)
RowOfThis(description, "Descripción", false)
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
DatePick(context = context, year = year, month = month, day = day)
}
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
TimePick(context = context, hours = hour, minutes = minutes)
}
Button(
onClick = {
if (title.value.isNullOrBlank() || description.value.isNullOrBlank()
) {
msg.value="Por favor ingrese todos los datos"
icon.value=Icons.Filled.Warning
showPopup.value=true
return#Button
}
scope.launch {
calendar.apply {
set(Calendar.YEAR,year.value)
set(Calendar.MONTH,(month.value-1))
set(Calendar.DAY_OF_MONTH,day.value)
set(Calendar.HOUR_OF_DAY,hour.value)
set(Calendar.MINUTE,minutes.value)
}
val shuff=(1..99999).shuffled().first()
vm.task.value.title = title.value
vm.task.value.description = description.value
vm.task.value.date = "${day.value}/${month.value}/${year.value}"
vm.task.value.time = calendar.timeInMillis
vm.task.value.dateCreated= getDateToday()
vm.task.value.shuff= shuff
vm.createTask(context, vm.task.value)
Log.e("tmepickerreceived","date and time :${year.value}/${month.value}/${day.value} : ${hour.value}:${minutes.value}")
val alarmMgr= context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent= Intent(context,AlarmReceiver::class.java)
intent.action="alarma"
intent.putExtra("ALARMA_ID_STRING","$shuff")
intent.putExtra("ALARMA_DESCRIPTION_STRING","${description.value}")
val pending=
PendingIntent.getBroadcast(context,shuff,intent, PendingIntent.FLAG_IMMUTABLE)
Log.e("time final","compare ${System.currentTimeMillis()}" +
" mytime: ${calendar.timeInMillis} " +
"hour: ${calendar.get(Calendar.HOUR_OF_DAY)} " +
"minute: ${calendar.get(Calendar.MINUTE)} " +
"year: ${calendar.get(Calendar.YEAR)} " +
"month: ${calendar.get(Calendar.MONTH)+1} " +
"day: ${calendar.get(Calendar.DAY_OF_MONTH)}")
alarmMgr?.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,pending)
msg.value="Recordatorio activado"
icon.value=Icons.Filled.Done
showPopup.value=true
vm.resetTask()
}
},
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
) {
Text(text = "Guardar", color = Color.White, style = NoteTheme.typography.subtitle)
}
}
}
and i have this alarm receiver:
class AlarmReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("alarm","************************received")
if (intent?.action == "alarma") {
val number = intent?.getStringExtra("ALARMA_ID_STRING")
val description=intent?.getStringExtra("ALARMA_DESCRIPTION_STRING")
val mp= MediaPlayer.create(context,R.raw.alarma)
mp.start()
if (context != null) {
if (number != null) {
val pendingResult: PendingResult = goAsync()
val asyncTask = Task(pendingResult,context,number.toInt())
asyncTask.execute()
showNotification(context,number.toInt(),"Recordatorio: ${number.toInt()}","$description")
}
}
}
}
private class Task(
private val pendingResult: PendingResult,
private val context: Context,
private val number:Int
) : AsyncTask<String, Int, String>() {
override fun doInBackground(vararg params: String?): String {
if (context != null) {
TaskDatabase.getDatabase(context).taskDao().deleteAfterAlarm(number)
}
return toString().also { log ->
Log.d("BACKGROUND", log)
}
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
// Must call finish() so the BroadcastReceiver can be recycled.
pendingResult.finish()
}
}
private fun showNotification(context: Context,idN:Int,title:String,text:String){
try{
val manager=context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val id= UUID.randomUUID().toString()
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
val channel= NotificationChannel(id,
UUID.randomUUID().toString(), NotificationManager.IMPORTANCE_HIGH)
manager.createNotificationChannel(channel)
}
val fullScreenIntent = Intent(context, MainActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(context, 0,
fullScreenIntent, PendingIntent.FLAG_IMMUTABLE)
var builder= NotificationCompat.Builder(context,id)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setFullScreenIntent(fullScreenPendingIntent,true)
manager.notify(idN,builder.build())
}catch (exc:Exception){
Toast.makeText(context,exc.toString(),Toast.LENGTH_LONG).show()
}
}
}
that methods works fine but if device is restarted the alarm does not work i have this in manifest too:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NotePadReminder"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="#string/app_name"
android:theme="#style/Theme.NotePadReminder">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<receiver android:name="com.mobile.notepadreminder.AlarmReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>

Related

Vaadin 14 - Error: Detected container element removed from DOM

Update 1: ============
After remove "window.ShadyDOM={force:true};" then it worked. But this is causing other problem ;):
https://vaadin.com/forum/thread/17399734/leverage-browser-save-password-feature
#Override
public void configurePage(InitialPageSettings settings) {
// TODO Auto-generated method stub
settings.addMetaTag("mobile-web-app-capable", "yes");
settings.addMetaTag("apple-mobile-web-app-capable", "yes");
settings.addMetaTag("apple-mobile-web-app-status-bar-style", "black");
settings.addInlineWithContents(
InitialPageSettings.Position.PREPEND, "window.customElements=window.customElements||{};"
+ "window.customElements.forcePolyfill=true;" + "window.ShadyDOM={force:true};",
InitialPageSettings.WrapMode.JAVASCRIPT);
}
End Update. ============
I am trying to integrate Payal checkout to Vaadin 14.7 (Spring core, not spring boot).
Here is paypal-view.js
import { LitElement, html, css } from "lit-element";
let buttons;
let hasRendered = false;
class PaypalElement extends LitElement {
static get properties() {
return {
mood: {
type: String,
noAccessor: false,
hasChanged(newVal, oldVal) {
console.log("newVal " + newVal + " oldVal " + oldVal);
},
},
};
}
static get styles() {
return [
css`
mood_color {
color: green;
}
#paypal-button {
size: "responsive";
}
`,
];
}
firstUpdated(_changedProperties) {
let testFname = this.shadowRoot.getElementById("fname");
super.firstUpdated(_changedProperties);
if (buttons && buttons.close && hasRendered) {
buttons.close();
hasRendered = false;
}
buttons = window.paypal.Buttons({
// Set up the transaction
createOrder: function (data, actions) {
return actions.order.create({
application_context: {
brand_name: "Brand name",
user_action: "PAY_NOW",
//No shipping for in-tangible merchant
shipping_preference: "NO_SHIPPING",
payment_method: {
payee_preferred: "IMMEDIATE_PAYMENT_REQUIRED", // Pending status transactions will not be allowed if you pass this parameter.
payer_selected: "PAYPAL",
},
},
purchase_units: [
{
soft_descriptor: "CC_STATEMENT_NAME",
amount: {
value: "5.00",
},
},
],
});
},
// Finalize the transaction
onApprove: function (data, actions) {
const elementText = document.getElementById("fname");
return actions.order.capture().then(function (orderData) {
// Successful capture! For demo purposes:
console.log(
"Capture result",
orderData,
JSON.stringify(orderData, null, 2)
);
let transaction = orderData.purchase_units[0].payments.captures[0];
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
document.getElementById("update-paypal-trans").innerHTML =
"update-paypal-trans = " + transaction.id;
// trigger lit event
testFname.value = transaction.id;
testFname.click();
document.getElementById("paypalelement").remove();
//console.log(elementText);
});
},
onError: function (error) {
console.log("onError", error, JSON.stringify(error, null, 2));
},
onCancel: function (data, actions) {
console.log("onCancel", data, JSON.stringify(data, null, 2));
document.getElementById("update-paypal-trans").innerHTML =
"testing 123";
// update shadow element
testFname.value = "12345 " + actions;
// trigger lit event
testFname.click();
},
});
// load paypal buttons and put them to element id="paypal-button-to-display" which is shadow dom
buttons
.render(this.shadowRoot.getElementById("paypal-button-to-display"))
.then(() => {
hasRendered = true;
})
.catch((err) => {
console.log(err)
// not mounted anymore, we can safely ignore the error
return;
});
}
// outside updates shadow element
updateShadow() {
this.shadowRoot.getElementById("test-update-shadow").innerHTML =
"test update shadow trans";
this.mood = "nice";
}
updateTask(e) {
console.log("updateTask: " + e);
}
updateTaskClick(e) {
console.log("updateTaskClick: " + e);
// call back-end
}
render() {
return html`
Web Components are
<span class="mood_color"> ${this.mood} and ${this.innerHTML}</span>!
<input
type="text"
id="fname"
name="fname"
value="${this.mood}"
#change=${(e) => this.updateTask(e.target.value)}
#click="${(e) => this.updateTaskClick(e.target.value)}"
/>
<div id="paypal-button-to-display"></div>
<br />
<div id="test-update-shadow">test-update-shadow-default</div>
<br />
<input
#click="${() => this.updateShadow()}"
id="myinput"
type="button"
value="update shadow button"
/>
`;
}
attributeChangedCallback(name, oldval, newval) {
super.attributeChangedCallback(name, oldval, newval);
console.log("attribute change: ", name, newval);
}
changeProperties() {
let randomString = Math.floor(Math.random() * 100).toString();
this.mood = "myProp " + randomString;
console.log("randomString change: ", randomString);
}
}
customElements.define("paypal-element", PaypalElement);
hello-world-view.ts
import { html, LitElement, customElement } from 'lit-element';
import './paypal-view';
import '#vaadin/vaadin-button';
import '#vaadin/vaadin-text-field';
#customElement('hello-world-view')
export class HelloWorldView extends LitElement {
createRenderRoot() {
// Do not use a shadow root
return this;
}
constructor() {
super();
}
render() {
return html`
<vaadin-text-field id="name" label="Your name"></vaadin-text-field>
<vaadin-button >Say hello</vaadin-button>
<paypal-elementt mood="great" id="paypalBut">hello customer</paypal-elementt>
`;
}
}
hello-world-view.ts
package com.lecompany.iad.view;
import com.lecompany.iad.app.MainView;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.littemplate.LitTemplate;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.template.Id;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
/**
* A Designer generated component for the stub-tag template.
*
* Designer will add and remove fields with #Id mappings but does not overwrite
* or otherwise change this file.
*/
#PageTitle("Hello World")
#Route(value = "hello", layout = MainView.class)
#Tag("hello-world-view")
#JsModule("./src/view/hello-world-view.ts")
public class HelloWorldView extends LitTemplate {
#Id
private TextField name;
// #Id
// private Button sayHello;
public HelloWorldView() {
UI.getCurrent().getPage().addJavaScript("https://www.paypal.com/sdk/js?client-id=AejZZjQsvxS299I2_LSnRkJStp0AsBzScCqbGK1_W6RNJssNR5NVnKYd97dM2kOJnRMF1u1ldLGjOlZ5&currency=USD");
// sayHello.addClickListener(e -> {
// Notification.show("Hello " + name.getValue());
// });
}
}
And here is error:
I tested above codes in Spring boot, then it works fine.
but it got error in the normal spring code. Any advice on this ?
There is reported issue for Paypal.
Paypal reported issue
It is a Vaadin bug and reported here:
Vaadin bug

Trying to reflect changes in Redux State from CurrentUser on React DOM for CurrentUser?

My app is a dashboard that allows the public to view certain items but not CRUD. If a user logs in, full CRUD is accessible. I'm using home spun JWT/Bcrypt auth in Rails backend and React/Redux for the frontend and state management. I'm wondering the best strategy to have the React DOM immediately reflect when a user login/logout and have certain items like create buttons appear/disappear based on login status. Right now, this.props.currentUser coming from the Redux store doesn't seem to help even though the Redux store has updated.
I'm using JSX ternary operators to display certain items based on currentUser state. I've tried this.props.currentUser ? <button>Example</button> : null or this.props.currentUser !== null ? <button>Example</button> : null and this.props.currentUser.length !== 0 ? <button>example</button> : null, none of which I get any consistency (might work for one compnonent but on page refresh no longer works, etc).
Here's an example component:
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import { Container, Grid, Image } from "semantic-ui-react";
import { connect } from 'react-redux';
import logo from "../../images/logo-2-dashboard";
import { clearCurrentUser } from "../actions/clearCurrentUserAction";
class Header extends Component {
logout = () => {
localStorage.clear();
this.props.clearCurrentUser()
this.props.history.push("/");
}
render() {
return (
<>
<Container fluid>
<Grid divided>
<Grid.Row columns={2}>
<Grid.Column>
<Image
src={logo}
size="large"
style={{ margin: "3px", padding: "2px" }}
></Image>
</Grid.Column>
<Grid.Column>
// Here's the kitchen sink approach lol
{this.props.currentUser && this.props.currentUser === null ||
this.props.currentUser && this.props.currentUser.length === 0 ? (
<Link
to={"/login"}
onClick={this.props.login}
style={{ marginLeft: "200px" }}
>
Login
</Link>
) : (
<Link
to={"/"}
onClick={this.logout}
style={{ marginLeft: "200px" }}
>
Logout
</Link>
)}
// SAME HERE
{this.props.currentUser && this.props.currentUser !== null ||
this.props.currentUser && this.props.currentUser.length !== 0 ? (
<div>Logged in as: {this.props.currentUser.username}</div>
) : null}
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
</>
);
}
}
const mapStateToProps = state => {
return {
currentUser: state.currentUser.currentUser
}
}
const mapDispatchToProps = dispatch => {
return {
clearCurrentUser: () => dispatch(clearCurrentUser())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Header));
Here is my Redux Action Thunk to set CurrentUser back to null on logout (I'm also clearing localHistory):
export const CLEAR_CURRENT_USER = 'CLEAR_CURRENT_USER'
export const clearCurrentUser = () => dispatch => {
return dispatch({ type: 'CLEAR_CURRENT_USER', payload: null })
}
and the Reducer for currentUser:
const initialState = {
currentUser: [],
};
export const currentUserReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_CURRENT_USER":
return { ...state, currentUser: action.payload }
case "GET_CURRENT_USER":
return { currentUser: action.payload }
case "CLEAR_CURRENT_USER":
return { currentUser: action.payload }
default:
return state;
}
};
Perhaphs this is the wrong approach altogether. I'm a junior working on my own at a company.
you are checking if currentUser is truthy but your initialstate is an array. your initialState for currentUser reducer should be null instead of an empty array.
const initialState = {
currentUser: null,
};
export const currentUserReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_CURRENT_USER":
return { ...state, currentUser: action.payload }
case "GET_CURRENT_USER":
return { currentUser: action.payload }
case "CLEAR_CURRENT_USER":
return { currentUser: action.payload }
default:
return state;
}
};

ReactNative IOS Testflight Firebase MapStateToProps Update Issue

I am having an extremely weird issue where I don't even know where to begin to debug since it only happens when I get the app into test flight. Basically I am trying to load channels based on geolocation. Some automatically load and then some are loaded if less than 100 miles from a mountain (lets call these PUBLIC and PRIVATE channels- both of which are in the same list). I have these 2 firebase calls in my action creator and push them into an array and then call dispatch after. I have an issue with the FlatList where it loads the PUBLIC channels and only when I scroll do the PRIVATE channels. There are a bunch of things I have tried including the most common from that specific github issue (flatlist updating) 'removeClippedSubviews={false}', extra data, pure components, etc, but none have worked.
Instead I found a way to get around this (I know it isn't the best, but I just want a solution that works for now) by just setting a timeout and waiting for the channels before dispatching the action:
setTimeout(function(){ dispatch(loadPublicChannelsSuccess(data)); }, 10);
Unfortunately, now is when the crazy issue comes in. Basically, this works for debug, release/ everything I have tried with XCode, but when it gets to my device the render method basically sits at a loading indicator until I switch tabs with react navigation. This makes no sense to me since it doesn't happen always (maybe 80%) of the time, and only in test flight so far. I had never seen this before setting the timeout either so not really sure where to begin:
render() {
const {loadPublicChannels, loading, publicChannels, checkedInMountain, selectedMountain} = this.props;
return !loadPublicChannels && publicChannels && !loading
? (
<MessagePanelPublic publicChannels={publicChannels} selectedMountain={selectedMountain}/>
) : (
<LoadingAnimation />
);
}
actions
export const getUserPublicChannels = () => {
return (dispatch, state) => {
dispatch(loadPublicChannels());
// get all mountains within distance specified
let mountainsInRange = state().session.mountainsInRange;
// get the user selected mountain
let selectedMountain = state().session.selectedMountain;
// see if the selected mountain is in range to add on additional channels
let currentMountain;
mountainsInRange
? (currentMountain =
mountainsInRange.filter(mountain => mountain.id === selectedMountain)
.length === 1
? true
: false)
: (currentMountain = false);
// mountain public channels (don't need to be within distance)
let currentMountainPublicChannelsRef = FIREBASE_REF_CHANNEL_INFO.child(
"Public"
)
.child(`${selectedMountain}`)
.child("Public");
// mountain private channels- only can see if within range (geolocation)
let currentMountainPrivateChannelsRef = FIREBASE_REF_CHANNEL_INFO.child(
"Public"
)
.child(`${selectedMountain}`)
.child("Private");
// get public channels
return currentMountainPublicChannelsRef
.orderByChild("key")
.once("value")
.then(snapshot => {
let publicChannelsToDownload = [];
snapshot.forEach(channelSnapshot => {
let channelId = channelSnapshot.key;
let channelInfo = channelSnapshot.val();
// add the channel ID to the download list
publicChannelsToDownload.push({ id: channelId, info: channelInfo });
});
// if mountain exists then get private channels/ if in range
if (currentMountain) {
currentMountainPrivateChannelsRef
.orderByChild("key")
.once("value")
.then(snapshot => {
snapshot.forEach(channelSnapshot => {
let channelId = channelSnapshot.key;
let channelInfo = channelSnapshot.val();
publicChannelsToDownload.push({
id: channelId,
info: channelInfo
});
});
});
}
return publicChannelsToDownload;
})
.then(data => {
setTimeout(function(){ dispatch(loadPublicChannelsSuccess(data)); }, 10);
});
};
};
reducer related to public channels
case types.LOAD_PUBLIC_CHANNELS:
return {
...state,
loadPublicChannels: true
};
case types.LOAD_PUBLIC_CHANNELS_SUCCESS:
console.log("PUBLIC");
console.log(action.publicChannels);
console.log(action);
return {
...state,
publicChannels: action.publicChannels,
loadPublicChannels: false,
messages: {}
};
case types.LOAD_PUBLIC_CHANNELS_ERROR:
return {
...state,
channelsPublicError: action.error,
loadPublicChannels: false
};
container which calls mapStateToProps and mapDispatchToProps
class MessagePanelPublicContainer extends Component {
constructor(props) {
super(props);
}
// get public and private channels from redux
async componentDidMount() {
this.props.getUserPrivateChannels();
this.props.loadCurrentUser();
// this.props.getUserPublicChannels();
}
componentDidUpdate(prevProps) {
if (this.props.mountainsInRange && prevProps.mountainsInRange !== this.props.mountainsInRange || prevProps.selectedMountain !== this.props.selectedMountain) {
this.props.getUserPublicChannels();
}
}
lessThan12HourAgo = (date) => {
return moment(date).isAfter(moment().subtract(12, 'hours'));
}
render() {
const {loadPublicChannels, loading, publicChannels, checkedInMountain, selectedMountain} = this.props;
return !loadPublicChannels && publicChannels && !loading
? (
<MessagePanelPublic publicChannels={publicChannels} selectedMountain={selectedMountain}/>
) : (
<LoadingAnimation />
);
}
}
const mapStateToProps = state => {
return {
publicChannels: state.chat.publicChannels,
loadPublicChannels: state.chat.loadPublicChannels,
currentUser: state.chat.currentUser,
loading: state.chat.loadCurrentUser,
mountainsInRange: state.session.mountainsInRange,
selectedMountain: state.session.selectedMountain,
};
}
const mapDispatchToProps = {
loadCurrentUser,
getUserPublicChannels,
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MessagePanelPublicContainer);
component
import React, { Component } from "react";
import { View, Text, FlatList, ImageComponent } from "react-native";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { ListItem, Icon, Button } from "react-native-elements";
import { withNavigation } from "react-navigation";
import LinearGradient from "react-native-linear-gradient";
import styles from "./Styles";
import moment from 'moment';
import FastImage from 'react-native-fast-image';
class MessagePanelPublicComponent extends Component {
render() {
// rendering all public channels
const renderPublicChannels = ({ item }) => {
return (
<ListItem
leftAvatar={{
source: { uri: item.info.ChannelPicture },
rounded: false,
overlayContainerStyle: { backgroundColor: "white" },
ImageComponent: FastImage
}}
title={item.info.Name}
titleStyle={styles.title}
chevron={true}
bottomDivider={true}
id={item.Name}
containerStyle={styles.listItemStyle}
/>
);
};
const renderText = () => {
return (
<View style={styles.extraTextContainer}>
<Text style={styles.extraText}>
Get within 100 miles from resort or select a closer resort to see more channels...
</Text>
<Icon
name="map-marker"
type="font-awesome"
size={40}
iconStyle={styles.extraIcon}
/>
</View>
);
};
return (
<View style={styles.container}>
<View style={styles.channelList}>
<FlatList
data={this.props.publicChannels}
renderItem={renderPublicChannels}
// keyExtractor={item => item.Name}
keyExtractor={(item, index) => index.toString()}
extraData={this.props.publicChannels}
removeClippedSubviews={false}
/>
{this.props.publicChannels.length < 3 ? renderText() : null}
</View>
</View>
);
}
}

IBM MFP onReadyToSubscribe method is not called

I have an iOS hybrid application written on IBM MFP 7.1 with angular. Currently I'm trying to use push notifications but the code never enters in onReadyToSubscribe method.
I get all the code from the documentation about the push notifications and still I have the problem.
My application-descriptor.xml is
<application xmlns="http://www.worklight.com/application-descriptor" id="B" platformVersion="7.1.0.00.20151227-1725">
<displayName>A</displayName>
<description>A</description>
<author>
<name>application's author</name>
<email>application author's e-mail</email>
<homepage>http://mycompany.com</homepage>
<copyright>Copyright My Company</copyright>
</author>
<mainFile>index.html</mainFile>
<features/>
<thumbnailImage>common/images/thumbnail.png</thumbnailImage>
<ipad bundleId="xxx.xxx.xxx" version="1.0" securityTest="PushSecurityTest" >
<worklightSettings include="false"/>
<pushSender password="123456"/>
<security>
<encryptWebResources enabled="false"/>
<testWebResourcesChecksum enabled="false" ignoreFileExtensions="png, jpg, jpeg, gif, mp4, mp3"/>
</security>
</ipad>
main.js file the one where we should have the magic
function wlCommonInit() {
PushAppRealmChallengeHandler.init();
WL.Client.connect({
onSuccess: connectSuccess,
onFailure: connectFailure
});
//---------------------------- Set up push notifications -------------------------------
if (WL.Client.Push) {
WL.Client.Push.onReadyToSubscribe = function() {
WL.SimpleDialog.show("Push Notifications", "onReadyToSubscribe", [ {
text : 'Close',
handler : function() {}
}
]);
$('#SubscribeButton').removeAttr('disabled');
$('#UnsubscribeButton').removeAttr('disabled');
WL.Client.Push.registerEventSourceCallback(
"myPush",
"PushAdapter",
"PushEventSource",
pushNotificationReceived);
};
}
}
function connectSuccess() {
WL.Logger.debug ("Successfully connected to MobileFirst Server.");
}
function connectFailure() {
WL.Logger.debug ("Failed connecting to MobileFirst Server.");
WL.SimpleDialog.show("Push Notifications", "Failed connecting to MobileFirst Server. Try again later.",
[{
text : 'Reload',
handler : WL.Client.reloadapp
},
{
text: 'Close',
handler : function() {}
}]
);
}
function loginButtonClicked() {
var reqURL = '/j_security_check';
var options = {
parameters : {
j_username : $('#usernameInputField').val(),
j_password : $('#passwordInputField').val()
},
headers: {}
};
PushAppRealmChallengeHandler.submitLoginForm(reqURL, options, PushAppRealmChallengeHandler.submitLoginFormCallback);
}
function isPushSupported() {
var isSupported = false;
if (WL.Client.Push){
isSupported = WL.Client.Push.isPushSupported();
}
alert(isSupported);
WL.SimpleDialog.show("Push Notifications", JSON.stringify(isSupported), [ {
text : 'Close',
handler : function() {}}
]);
}
function isPushSubscribed() {
var isSubscribed = false;
if (WL.Client.Push){
isSubscribed = WL.Client.Push.isSubscribed('myPush');
}
WL.SimpleDialog.show("Push Notifications", JSON.stringify(isSubscribed), [ {
text : 'Close',
handler : function() {}}
]);
}
// --------------------------------- Subscribe ------------------------------------
function doSubscribe() {
WL.Client.Push.subscribe("myPush", {
onSuccess: doSubscribeSuccess,
onFailure: doSubscribeFailure
});
}
function doSubscribeSuccess() {
WL.SimpleDialog.show("Push Notifications", "doSubscribeSuccess", [ {
text : 'Close',
handler : function() {}}
]);
}
function doSubscribeFailure() {
WL.SimpleDialog.show("Push Notifications", "doSubscribeFailure", [ {
text : 'Close',
handler : function() {}}
]);
}
//------------------------------- Unsubscribe ---------------------------------------
function doUnsubscribe() {
WL.Client.Push.unsubscribe("myPush", {
onSuccess: doUnsubscribeSuccess,
onFailure: doUnsubscribeFailure
});
}
function doUnsubscribeSuccess() {
WL.SimpleDialog.show("Push Notifications", "doUnsubscribeSuccess", [ {
text : 'Close',
handler : function() {}}
]);
}
function doUnsubscribeFailure() {
WL.SimpleDialog.show("Push Notifications", "doUnsubscribeFailure", [ {
text : 'Close',
handler : function() {}}
]);
}
//------------------------------- Handle received notification ---------------------------------------
function pushNotificationReceived(props, payload) {
WL.SimpleDialog.show("Push Notifications", "Provider notification data: " + JSON.stringify(props), [ {
text : 'Close',
handler : function() {
WL.SimpleDialog.show("Push Notifications", "Application notification data: " + JSON.stringify(payload), [ {
text : 'Close',
handler : function() {}}
]);
}}
]);
}
And the last magic js file handles the authentication on the MFP server
var PushAppRealmChallengeHandler = (function(){
var challengeHandler;
function init() {
challengeHandler = WL.Client.createChallengeHandler("PushAppRealm");
challengeHandler.isCustomResponse = isCustomResponse;
challengeHandler.handleChallenge = handleChallenge;
challengeHandler.submitLoginFormCallback = submitLoginFormCallback;
}
function isCustomResponse(response) {
if (!response || response.responseText === null) {
return false;
}
var indicatorIdx = response.responseText.search('j_security_check');
if (indicatorIdx >= 0){
return true;
}
return false;
}
function handleChallenge(response) {
$('#AppBody').hide();
$('#AuthBody').show();
$('#passwordInputField').val('');
}
function submitLoginFormCallback(response) {
var isLoginFormResponse = challengeHandler.isCustomResponse(response);
if (isLoginFormResponse){
challengeHandler.handleChallenge(response);
} else {
$('#AppBody').show();
$('#AuthBody').hide();
challengeHandler.submitSuccess();
}
}
function submitLoginForm(url, options, callback) {
challengeHandler.submitLoginForm(url, options, callback)
}
return {
init: init,
submitLoginForm: submitLoginForm,
submitLoginFormCallback: submitLoginFormCallback
}
})();
I already checked the certificate and it is okay, also I redeploy everything when I add the certificate.
Do you have some ideas where I can have a problem?
When onReadyToSubscribe should be called?
Is it related with the authentication of the application?
Thanks in advance
This was an issue with Apple Sandbox APNs not providing token as reported in the following links:
https://forums.developer.apple.com/message/155239#155239
https://forums.developer.apple.com/thread/52224

IE 11 changing URL

I am getting strange behaviour in IE 11.
When I go to my web application using URL
"hostname:port/myapp-web/app/login.jsp"
The login page is displayed, And Login is done successfully.
Now. Problem is that, after logging in, App's landing page is index.html.
So URL should be "hostname:port/myapp-web/app/index.html"
Instead, IE changes it to "hostname:port///index.html"
Now, when I try to do any other operation or navigation, it fails because base URL is changed and my JS code cannot find app context root and all AJAX calls fails.
I tried searching over internet for the same, but couldn;t find any answer.
Please help if anyone has idea about such behaviour.
P.S. App is working fine in IE: 8/9, Chrome and FF.
I found something related to UTF-* character URLs but my app uses plain text URL with NO special characters.
App is developed using Spring for server side and KnockoutJS, HTML for UI.
Thanks in advance for the help.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=EDGE" />
<!-- script includes -->
</head>
<body>
<!-- NavigationBar -->
</body>
<script type="text/javascript">
app.initialize(); // app.js
$.getJSON('/myapp-web/Security/authorise', function (response) {
app.common.navbar.reRenderNavBar(response);
app.navigation = new Navigation("AdminHome"); // navigation.js
// This navigation causes IE11 to change URL to http://host:port///#AdminHome
// it should be // http://host:port/myapp-web/app/index.html#AdminHome
});
</script>
</html>
Navigation.js
var ua = window.navigator.userAgent
var msie = ua.indexOf("MSIE ")
var ieVer = -1;
if (msie > 0) {
var ieVer = ua.substring(msie + 5, ua.indexOf(".", msie));
//console.log(ieVer);
}
var NavigationInput = function (pName, pValue) {
this.paramName = pName;
this.paramValue = pValue;
this.toString = function () {
return pName + ":" + pValue;
}
}
var Navigation = function (startupView) {
var self = this;
this.navInput = [];
this.navViewModel = null;
this.navViewModelInitComplete = false;
// this.navigate = function navigate(view) {
//
// if (view !== this.currentView) {
// self.loadView(view, true, null);
// }
// }
this.navigateWithParams = function navigateWithParams(view, params) {
self.loadView(view, true, params);
}
this.goBack = function goBack() {
history.go(-1);
//history.back();
}
this.loadView = function (view, pushHistory, params) {
var contentframe = $("#content");
//app.consolePrintInfo("navigation", "previous view: " + self.currentView + " new view: " + view);
if (typeof (self.currentView) != 'undefined' && self.currentView
&& self.currentView.toLowerCase() == view.toLowerCase()
&& isParamsEqual(params)) {
return;
}
var constructedView;
constructedView = "Views/" + view + "/" + view + ".html"
contentframe.load(constructedView, function () {
self.currentView = view;
modUrl = view;
if (params != null) {
if (params instanceof String) {
modUrl = params;
}
else {
var queryStr = self.convertParamsToQueryString(params);
modUrl += "?" + queryStr;
}
// if (typeof(app.navigation.navViewModel) != 'undefined'
// && app.navigation.navViewModel
// && !app.navigation.navViewModelInitComplete)
// {
// app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(self.convertQueryStringToParams(modUrl));
// }
}
if (pushHistory) {
if (ieVer > 6) {
window.history.pushState(view, null, modUrl);
}
else {
window.history.pushState(view, null, "#" + modUrl);
}
}
app.consolePrintInfo("navigation", "modified url:" + modUrl + " view model: " + app.navigation.navViewModel);
var navInputs = self.convertQueryStringToParams(modUrl);
self.urlInputs = navInputs;
app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(navInputs);
//$.getScript("Views/" + view + ".js", function () {
//});
});
isParamsEqual = function (iParams) {
if ((typeof(self.urlInputs) == 'undefined' || !self.urlInputs)
&& (typeof(iParams) == 'undefined' || !iParams)) {
return true;
}
else if (app.utility.isObjectNull(self.urlInputs) && app.utility.isObjectNull(iParams)) {
return true;
}
else {
return false;
}
}
}
this.convertParamsToQueryString = function (params) {
var result = "";
for (var i = 0; i < params.length; i++) {
if (i > 0) {
result += "&";
}
result += params[i].paramName + "=" +
params[i].paramValue;
}
return result;
};
this.convertQueryStringToParams = function (modUrl) {
var inputs = null;
var fragments = modUrl.split("?");
if (fragments && fragments.length == 2) {
var f = fragments[1].split("&");
if (f && f.length > 0) {
for (var i = 0; i < f.length; i++) {
var inp = f[i].split("=");
if (inputs == null) inputs = [];
inputs.push(new NavigationInput(inp[0], inp[1]));
}
}
}
return inputs;
};
this.back = function () {
if (history.state) {
var view = self.getView();
self.loadView(view, false, self.convertQueryStringToParams(location.href));
} else {
var view = self.getView();
self.loadView(view, true, self.convertQueryStringToParams(location.href));
}
};
this.getView = function () {
var fragments = location.href.split('#');
if (fragments && fragments.length === 2) {
var inFrag = fragments[1].split('?');
if (inFrag && inFrag.length === 2) {
return inFrag[0];
}
else {
return fragments[1];
}
} else {
return startupView;
}
};
this.loadView(this.getView(), true, this.convertQueryStringToParams(location.href));
$(window).on('popstate', self.back);
}
app.js:
-----------------
app = {};
// utilities
app.utility = {};
app.ui = {};
// common
app.common = {};
// validation
app.validation = {};
// common components
app.common.navbar = {};
app.common.authorisation = {};
app.initialize = function () {
$.blockUI.defaults.message = '<h4><img src="images/busy.gif" /> Processing...</h4>';
$.blockUI.defaults.css.border = '2px solid #e3e3e3';
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
//$(document).click(function() { $(".popover").remove(); });
}
app.consolePrintInfo = function (tag, message) {
if (typeof(console) != 'undefined' && console)
console.info(tag + ": " + message);
}
app.ui.showAppError = function (message) {
app.consolePrintInfo("App", "displaying error message: " + message);
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-info');
$('#error-console').addClass('alert-error');
$('#error-console').html(message);
}
app.ui.showAppInfo = function (message) {
app.consolePrintInfo("App", "displaying info message: " + message);
$('#error-console').show();
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-error');
$('#error-console').addClass('alert-info');
$('#error-console').html(message);
$('#error-console').fadeOut(4000);
}
app.utility.addQueryParameter = function (url, paramName, paramValue) {
var rUrl = url;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
if (rUrl.indexOf("?") != -1) {
rUrl = rUrl + "&" + paramName + "=" + paramValue;
}
else {
rUrl = rUrl + "?" + paramName + "=" + paramValue;
}
}
return rUrl;
}
app.utility.addSearchParameter = function (paramName, paramValue) {
var rValue = undefined;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
rValue = paramName + ":" + paramValue;
}
return rValue;
}
app.utility.searchParameter = function (inputKeyArray, paramName) {
if (inputKeyArray instanceof Array) {
for (var i = 0; i < inputKeyArray.length; i++) {
if (inputKeyArray[i].paramName == paramName) {
return inputKeyArray[i].paramValue;
}
}
}
return undefined;
}
app.utility.isObjectNull = function (obj) {
return typeof(obj) == 'undefined' || obj == undefined || !obj;
}
app.utility.isObjectNotNull = function (obj) {
return typeof(obj) != 'undefined' && obj;
}
app.utility.isFunction = function (obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
app.utility.parseError = function (em) {
if (!app.utility.isObjectNull(em)) {
jem = JSON.parse(em);
var keyArray = new Array();
keyArray.push(jem.errorCode);
keyArray.push(jem.errorMessage);
return keyArray;
}
else {
return undefined;
}
}
app.utility.showAppErrorDialog = function (errTitle, errMessage) {
if (!app.utility.isObjectNull(errMessage)) {
var $message = $("Error:" + errMessage)
.dialog({autoOpen: false, width: 300, title: errTitle, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showErrorDialog = function (err) {
if (!app.utility.isObjectNull(err)) {
var $message = $('<div><p>Unfortunately, there has been error in the server!</p><p>' + err[1] + '</p><p>Please send the screenshot to developer team</div>')
.dialog({autoOpen: false, width: 300, title: err[0], modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showDialog = function (heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text)) {
var $message = $('<div><p>' + text + '</p></div>')
.dialog({autoOpen: false, width: 300, title: heading, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.populateToolTip = function () {
$("img[id^='tooltip']").each(function () {
var idName = $(this).attr("id");
$('#' + idName).tooltip('toggle');
$('#' + idName).tooltip('hide');
});
};
app.utility.isNotEmptyNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) && ("" + input).indexOf("-") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNotEmptyWholeNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) &&
("" + input).indexOf("-") == -1 && ("" + input).indexOf(".") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNumberValue = function (input) {
if (!isNaN(input) && isFinite(input)) {
return true;
}
return false;
};
app.utility.doHttpRequest = function (input) {
if (app.utility.isObjectNull(input) || app.utility.isObjectNull(input.rURL)) {
app.utility.showDialog("Error!", "Unable to find required inputs. Error in sending request");
return false;
}
app.consolePrintInfo("HTTP REQUEST: ", "[URL] :" + input.rURL);
app.consolePrintInfo("HTTP REQUEST: ", "[Type] :" + input.rType);
app.consolePrintInfo("HTTP REQUEST: ", "[Input] :" + input.rDataToSend);
$.ajax({
url: input.rURL,
type: input.rType,
contentType: 'application/json',
cache: false,
data: input.rDataToSend,
dataType: 'json'
}).success(function (response) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - success] :" + JSON.stringify(response));
if (!app.utility.isObjectNull(input.rOnSuccessFunction)) {
input.rOnSuccessFunction(response);
}
else if (!app.utility.isObjectNull(input.rOnSuccessMessage)) {
app.utility.showDialog("Complete", input.rOnSuccessMessage);
}
}).error(function (response) {
if (response.status == 401) {
// session expired. redirect to login page.
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Session Expired");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Session Expired', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
// Remove the cached data
//comp_storage.remove("lastStoredValue");
//comp_storage.remove("permissionStr");
//window.open("/aid-web/logout", "_self");
app.utility.doLogout();
}
}}
);
$message.dialog('open');
}
else if (response.status == 400) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Server Error");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Server Error', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
else {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] :" + response.responseText);
if (!app.utility.isObjectNull(input.rOnErrorFunction)) {
input.rOnErrorFunction(response.responseText);
}
else if (!app.utility.isObjectNull(input.rOnErrorMessage)) {
app.utility.showDialog("Error", input.rOnErrorMessage);
}
}
});
};
app.utility.doLogout = function () {
comp_storage.remove("lastStoredValue");
comp_storage.remove("permissionStr");
window.open("/aid-web/logout", "_self");
};
// common
// Nav bar component
app.common.navbar.reRenderNavBar = function (content) {
// [SAMPLE] To update the common component. create a view model of that
// component. set the needed variables.
// and *definately call applyBindings()*
app.common.navbar.navBarViewModel = new ko.navBarComponent.viewModel({
// set compt. values if needed. like below.
//navBarComponent_isEmpty:ko.observable(false)
});
app.common.navbar.navBarViewModel.navBarComponent_reRender(content);
ko.applyBindings(app.common.navbar.navBarViewModel, $('#nav-bar').get(0));
}
// Authorisation component
app.common.authorisation.storeRoleInfo = function (permissionArr) {
comp_auth.storeRoleInfo(permissionArr);
};
app.common.authorisation.isRolePresent = function (roleName) {
return comp_auth.isRolePresent(roleName);
};
// validation
app.validation.highlightElement = function (id, text) {
}
app.validation.highlightError = function (eleId, heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text) && !app.utility.isObjectNull(eleId)) {
$("#" + eleId).addClass("ui-state-error");
var $message = $('<div><p>' + text + '</p></div>')
.dialog({
autoOpen: true,
width: 300,
title: heading, modal: true,
close: function () {
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
},
buttons: {
Ok: function () {
$(this).dialog("close");
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
}
},
overlay: {
opacity: 0.1,
},
}
).parent().addClass("ui-state-error");
}
}

Resources