How can I check if the user denied or accepted the push notification permission message in ios in codenameone or native?
Both Android and iOS have API's to detect if push is enabled:
Push Notification ON or OFF Checking in iOS
Android 4.1: How to check notifications are disabled for the application?
Since those were added relatively recently and we didn't get enough demand for that we don't support them at this time. You can probably invoke them with a native interface or submit a pull request with integration. Normally you would get a push registered callback when push works and an error or nothing if it doesn't.
I found a solution implementing a funtion native to IOS 10
This methods are working perfectly in Objective-c and codenameone code
//------------------------------------------------------------------------------
//This method is use to check if the user enable or disable push notification
//------------------------------------------------------------------------------
-(BOOL)isPushNotificationIsEnable{
if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
NSLog(#"isPushNotificationIsEnable()->YES");
return YES;
} else {
NSLog(#"isPushNotificationIsEnable()->NO");
return NO;
}
}
//------------------------------------------------------------------------------
//This method is use to launch the Notification screen of your app
//------------------------------------------------------------------------------
Display.getInstance().execute("App-Prefs:root=NOTIFICATIONS_ID&path=your package name app", new ActionListener() {
String methodName = "startLocationSetting";
#Override
public void actionPerformed(ActionEvent evt) {
boolean status = Utils.isPushNotificationEnable();
}
});
//------------------------------------------------------------------------------
Related
I have developed a single page application with React and MobX. To get some progress information from backend code such as copying a file progress, I use Server Sent Events and EventSource at javascript code. In any browser, I can get the event messages and show progresses successfully. React gets changes from the EventSource onmessage event and renders the changes on the screen. Here is how I add EventSource to my js code. (For the ones who ask if the message format of eventsource is correct? Yes, it is. It is working on browsers.)
Code:
fetchEvents(url) {
let evtSource = new EventSource(url);
evtSource.onmessage = (message) => {
const data = JSON.parse(message.data);
//assign data to an observable variable
}
}
However, I need my single page application to be embeded in a Java application. For this, I use JavaFX WebEngine and WebView to load my React application. Every functionalities work well except Server Sent Events and EventSource messages. onmessage(), onopen(), onerror() methods are not called. Thus, I can't get the changes of data to be shown on the screen. I can't get any information via EventSource at my javascript code. Here is the JavaFX code;
Code:
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("localhost");
WebView myBrowser = new WebView();
WebEngine myWebEngine = myBrowser.getEngine();
myWebEngine.setJavaScriptEnabled(true);
myWebEngine.load("http://localhost:8080");
StackPane root = new StackPane();
root.getChildren().addAll(myBrowser, reloadButton);
primaryStage.setScene(new Scene(root, 800, 640));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Does JavaFX WebView not support EventSource and Server Sent Events? I am curious about is there any way to make SSE work in JavaFX WebView? Or are there any other possible solutions to embed my single page application in Java code with EventSource and Server Sent Events working well.
Thank you.
I have created an app using Codename One but I am having trouble with the push notifications on Android.
The issue happens when opening a push notification when the app isn't open in the background.
When it tries to use any resources from the theme it causes a NullPointerException. The theme is initialised in the init() method but doesn't appear to happen when opening the push notification.
If I then initialise the theme in the same method as the null pointer, just before it happens, it works. It then goes on to cause a null pointer further on in the method.
Why do some objects not appear to be initialised on android when opening a push notification when the app is not open in the background?
The line that originally causes the NullPointerException when using the theme is
Image icon = theme.getImage("ADINlogoRound.png");
My init method is
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
Resources css = null;
try {
css = Resources.openLayered("/theme.css");
} catch (IOException ex) {
}
UIManager.getInstance().addThemeProps(css.getTheme(css.getThemeResourceNames()[0]));
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
Log.bindCrashProtection(true);
Display.getInstance().lockOrientation(true);
}
It appears that in android the init and start methods are not called when the app is opened from a push notification. Whatever you do in those methods should also be done in the push method.
I am at the final stage of my codename one app now and this final stage is to implement push notifications.
I need some help on how to implement the client side for push notifications.
I have followed the section in the developer guide and my main class implements PushCallback.
I also have the relevant methods implemented as below:
public void start() {
if(current != null){
current.show();
return;
}
Display.getInstance().callSerially(() -> Display.getInstance().registerPush());
showHomeForm();
}
#Override
public void push(String value) {
Dialog.show("Received Push", value, "OK", null);
}
#Override
public void registeredForPush(String deviceId) {
Dialog.show("Push Registered", "Device ID: " + deviceId + "\nDevice Key: " + Push.getDeviceKey() , "OK", null);
}
#Override
public void pushRegistrationError(String error, int errorCode) {
Dialog.show("Push Error", "" + error, "OK", null);
}
My understanding is that the registeredForPush method should be invoked when calling the registerPush method. When I start the app the registeredForPush method is not called and the registerPush method seems to do nothing.
What is incorrect in my understanding?
You shouldn't use a Dialog in these callbacks as a dialog call is blocking and might cause a failure because of the nature of these API's e.g. an API can be invoked when the app is minimized.
registerPush() triggers the registration and should eventually invoke either the registered or the error method.
I'm guessing you are running on the simulator where push isn't actually implemented. You can use the new push console that allows you to simulate it by invoking the registered callbacks and send push messages to the simulator. These will only work on the devices.
I'm having trouble following the second step here.
I really don't understand how this sample does anything other than return a simple toast message. How does it utilize the API to display that message?
class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
I'm afraid my this sample is too complex for my limited knowledge. How exactly do I "talk" to the Google Endpoints Module when running an app? Specifically, What is EndpointsAsyncTask();?
Are there any resources listing all the methods available to me? Is there a simpler example of an app communicating with a Google Cloud Endpoint?
The service methods available to you are defined by the backend source in section 1.
In the example you posted, this line: myApiService.sayHi(name).execute()
is an actual invocation call to the backend that you defined by annotating #ApiMethod("sayHi") on the method in the MyEndpoint.java class of your backend module.
The reason your Android app defines an EndpointsAsyncTask is because slow operations such as calls that hit the network need to happen off of the UI thread to avoid locking the UI. The demo simply puts the returned value into a Toast but you could modify onPostExecute() to do whatever you'd like with the result.
For more info on Google Endpoints check out:
https://cloud.google.com/appengine/docs/java/endpoints/
And for info about using an Android AsyncTask look here:
http://developer.android.com/reference/android/os/AsyncTask.html
UPDATE: The plot thickens. I changed my channel name and it is suddenly working (which means it wasn't a problem with my push service, since I'm getting the same HTTP response from the Microsoft Push Notification server).
To me, however, this is not a solution. How will I be able to test this and KNOW my users are getting their push notifications if I'm getting the same response when it's not working as I do when it is?
[ORIGINAL POST]
I've been trying to get push notifications sent to my Windows Phone 7 device, but I'm having very big problems that I can't find any answers for. I'll start with the c# code.
I set up push notifications using the following C# code.
private HttpNotificationChannel channel;
private static string PUSH_CHANNEL = "MySpecialPushChannel";
private Uri PushUri = null;
private bool IsPushRegistered = false;
public void StartPushSubscription()
{
try
{
channel = HttpNotificationChannel.Find(PUSH_CHANNEL);
}
catch
{}
if (channel != null)
{
PushUri = channel.ChannelUri;
if (!channel.IsShellTileBound)
channel.BindToShellTile();
}
else
{
channel = new HttpNotificationChannel(PUSH_CHANNEL);
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
channel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(channel_HttpNotificationReceived);
channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(channel_ErrorOccurred);
try
{
channel.Open();
channel.BindToShellTile();
}
catch (Exception err)
{
channel = null;
IsPushRegistered = false;
// Code to try again
}
}
}
void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
PushUri = e.ChannelUri;
IsPushRegistered = true;
}
I'm following the standard WP7 push structure:
Find the HttpNotificationChannel (or start a new one)
Register event handler to get the push notification uri back
Open the channel
Bind to the tile
Handle the channel Uri (which we send to our service to await the happy day when we send the push notification
OK... so far so good. No errors, I get my Uri, send it to my service just fine. I pin my app to the start screen and my service sends a push request to the Uri (sending just the count so that I get a little push count number in the upper right hand corner). I get back an HTTP 200 status with the following:
DeviceConnectionStatus => Connected
NotificationStatus => Received
SubscriptionStatus => Active
And then... nothing. No push status shows up on my app. I've now tried it on my device, in the emulator, on another device, and with multiple servers and the result is always the same. Everything looks like it is working except for the fact that it doesn't work.
To me, however, this is not a solution. How will I be able to test this and KNOW my users are getting their push notifications if I'm getting the same response when it's not working as I do when it is?
The answer is, you can't. It's a limitation of how WP7 handles notifications.
For structured notifications like Tile and Toast, if you get the Connected/Active/Received/200 response, then you can know that MPNS accepted your notification request. However, this does not mean that you have sent a valid XML payload.
The component that handles parsing XML is the Push Client, the process running on the phone that accepts push notifications and deals them out to appropriate applications, displays the toast, etc.
If you have sent invalid XML, there is absolutely no indication that you've done so. At most, if you try to send the notification again to that same push channel URI, you'll get a 404 in response. Apparently getting an invalid XML payload for a specific application makes that application's push channel close, requiring you to go through the whole procedure again.
I've discovered this while debugging with our server team, and through trying to get the phone to display an alternate live tile. The only advice I can offer you is to quadruple-check your XML.
You will get errors in your error event handler for your push notification channel for Toast notifications that have invalid XML, since you are able to send/receive toast notifications while the application is active.
If anyone from Microsoft is reading this, PLEASE provide more thorough documentation on possible error states in the push notification system. We also need an event handler for Tile notifications, or at least allow us to receive tile notifications while the app is in the foreground and fire the notification channel error event so that we can be aware that our XML payload is invalid.
Especially if your web service isn't built with WCF, .NET, Azure, and whatever, working with Push Notifications on WP7 is like wandering blind.
Documentation for an exception message reading "InvalidOperationException(Failed to open channel)" should not read: "This exception is raised when the notification channel failed to open. Try opening the notification channel again." (reference)
are you getting the URL from each device? you need to get a URL from the push notification sevice for each device everytime your device connects,
when it does you need to find a way of retrieving the url from each client,
once you do that and your still not receiving push notifications then I would write to microsoft to see if they can see anything to do with the push notifications