I'm having trouble getting Push Notifications when the app is in foreground in an Android device. As soon as I put the app in the background all goes well.
This is the java code I use to send de notifications:
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(URL_SERVER);
List<NameValuePair> arguments = new ArrayList<>();
arguments.add(new BasicNameValuePair("token", TOKEN));
arguments.add(new BasicNameValuePair("device", codigoApp));
arguments.add(new BasicNameValuePair("type", "1"));
arguments.add(new BasicNameValuePair("body", ip));
arguments.add(new BasicNameValuePair("auth", GOOGLE_AUTH));
try {
httpPost.setEntity(new UrlEncodedFormEntity(arguments));
HttpResponse response = client.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
} catch (IOException ex) {
Logger.getLogger(NotificaReview.class.getName()).log(Level.SEVERE, null, ex);
}
And this is the code in the app:
public void start() {
if(current != null){
current.show();
return;
}
if (Push.getPushKey() != null)
devicePush = Push.getPushKey();
else
Display.getInstance().registerPush();
Form inicioGUI = new InicioGUI(devicePush);
inicioGUI.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
#Override
public void push(String value) {
ToastBar.showMessage("Archivo recibido correctamente con IP" + value, FontImage.MATERIAL_INFO);
}
#Override
public void registeredForPush(String deviceId) {
devicePush = deviceId;
}
#Override
public void pushRegistrationError(String error, int errorCode) {
}
The ToastBar only shows when I bring the app to foreground after receiving the push while in background. The Push callback is never called if the app is alive.
Any ideas?
I need answers to my comment in the question which might help explain the issue. I'll edit this answer based on the updates to the question.
In the meantime I see several issues in the code. See my highlighted comments/fixes below:
public void start() {
if(current != null){
current.show();
return;
}
// don't check the push key, always register the device and
// always do it in a callSerially as it might trigger a prompt
callSerially(() -> registerPush());
Form inicioGUI = new InicioGUI(Push.getPushKey());
inicioGUI.show();
}
#Override
public void push(String value) {
ToastBar.showMessage("Archivo recibido correctamente con IP" + value, FontImage.MATERIAL_INFO);
}
#Override
public void registeredForPush(String deviceId) {
// deviceId is the native push key you need to use the actual
// push key value never device ID
devicePush = Push.getPushKey();
}
#Override
public void pushRegistrationError(String error, int errorCode) {
// you might have gotten a push error which might have explained the
// cause of the problem
Log.p("Push error " + errorCode + ":" + error);
Log.sendLogAsync();
}
Related
I'm trying to get the direction of the upcoming turn while travelling, i.e. I want to trigger an event in my app according to the direction of the upcoming turn.
I've tried using event listeners, taking help of the documentation and the provided examples but as I'm pretty new to android studio and mapbox, I've not been successful (my app either crashed or the function would never get triggered). I've also tried searching for getting the voice commands into text form or log form but have failed.
While my current code does display directions and gives voiced instructions, I can't figure out how to access either of them. I'd like to know if there's a simple way of achieving what I'm after without using any event listeners.
private MapView mapView;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private MapboxNavigation navigation;
private Button button;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
//Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
mapboxMap.addOnMapClickListener(MainActivity.this);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
Log.d(TAG, "addDestinationIconSymbolLayer: " + geoJsonSource);
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
#SuppressWarnings( {"MissingPermission"})
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
Log.d(TAG, "Does this even work");
Log.d(TAG, "onMapClick: " + source.toString());
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
// Add the mapView's own lifecycle methods to the activity's lifecycle methods
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
It sounds like you might want to look at using an event listener for a custom milestone. Here's a link to the docs:
https://docs.mapbox.com/android/navigation/overview/milestones/#milestone-event-listener
I'm making an application which has to detect a bluetooth card reader and if a card is inserted or removed from this one.
I'm using an API for the android part in my native interface so I implement two callback functions from an interface which concerns the bluetooth card reader detection and two other callback functions which concerns the detection of cards in the bluetooth card reader.
Two callback functions which are called when the bluetooth card reader is detected and the two others which are called when a card is inserted or removed from the device.
I have no problem with the callback which are called when the bluetooth card reader is detected but the application never calls the functions which must be called when the card are inserted or removed.
public class FtReaderNativeImpl implements BluetoothRead.CardListener,BluetoothRead.ReaderListener{
private BluetoothRead btRead;
ArrayList<BluetoothDevice> listRead;
public String scanBluetooth(){
String chaine ="";
if (Looper.myLooper() == null)
{
Looper.prepare();
}
Log.p("btread avant init:"+btRead);
btRead = new
BluetoothRead(com.codename1.impl.android.AndroidNativeUtil.getContext());
btRead.setCardListener(this);
btRead.setReaderListener(this);
ReturnCode rc = btRead.btInitLib();
Log.p("btread après init:"+btRead);
Log.p("rc:"+rc);
return chaine;
}
#Override
public void CardInserted()
{
//showMessage("onCardInserted");
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "INSERTED", Toast.LENGTH_SHORT).show();
chaine+=btRead.getName();
chaine+=btRead.getFirstName();
eidReader.showDialog("INSERTED "+chaine);
Log.p("btInsertOK");
}
#Override
public void CardRemoved()
{
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "REMOVED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("REMOVED "+chaine);
Log.p("btRemoveNOK");
}
#Override
public void ReaderConnected(BluetoothDevice bluetoothDevice)
{
/*Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "CONNECTED", Toast.LENGTH_SHORT).show();*/
EidReader.showDialog("CONNECTED");
Log.p("onReaderConnected: " + bluetoothDevice.getName());
if (btRead.btOpen(bluetoothDevice) == ReturnCode.OK) {
Log.p("btOpen OK");
} else {
Log.p("btOpen NOK");
}
Log.p("btread après listener:"+btRead);
}
#Override
public void ReaderDisconnected(BluetoothDevice bluetoothDevice)
{
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "DISCONNECTED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("DISCONNECTED");
}}
ScanBluetooth is just a initialization method which is called in the beginning of the form:
public class EidReader extends Form implements HasLogger {
Container loggatt = new Container();
private Bluetooth bt;
private static Container devicesCnt;
private Map devices = new HashMap();
Form main = this;
FtReaderNative frn;
public EidReader(Form parent)
{
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Display dis = Display.getInstance();
frn = (FtReaderNative)NativeLookup.create(FtReaderNative.class);
if(dis.getPlatformName().compareTo("and")==0){
LocationManager lm = LocationManager.getLocationManager();
}
bt = new Bluetooth();
frn.scanBluetooth();
//combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(),new MultiButton()));
this.add(new Button(new Command("enable bluetooth")
{
#Override
public void actionPerformed(ActionEvent evt){
try {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
this.add(new Button(new Command("initialize")
{
#Override
public void actionPerformed(ActionEvent evt)
{
try {
bt.initialize(true, false, "bluetoothleplugin");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
Button bttest = new Button("DISPLAY READER");
bttest.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
DeleteUI();
StringTokenizer st = new StringTokenizer(frn.infoDevices());
while (st.hasMoreTokens()) {
MultiButton mb = new MultiButton(st.nextToken());
mb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
devicesCnt.add(new SpanLabel(frn.readerStatus( mb.getTextLine1())));
}});
devicesCnt.add(mb);
}
}
});
this.add(bttest);
devicesCnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
devicesCnt.setScrollableY(true);
this.add(devicesCnt);
this.show();
}
private void DeleteUI()
{
devicesCnt.removeAll();
devicesCnt.revalidate();
}
#Override
public String getLogName()
{
// TODO Auto-generated method stub
return null;
}
public static void showDialog(String txt)
{
//Display.getInstance().callSerially(()->
//{
devicesCnt.add(new SpanLabel(txt));
devicesCnt.forceRevalidate();
//});
}
}
I've tested Geofence example by cn1 where it sets local notification. When the app is closed(get destroyed), it still gives notification. But I want to get location through GPS and run connectionRequest to save them in the server. I replaced the connectionRequest code instead of LocalNotification in following code but it doesnot work. What should I do to run the connectionRequest when the app is closed(not when it is minimized but destroyed) so that once the user installs and close (destroys) it, the app sent his/her location data in the server forever untill the app is uninstalled.
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
Geofence with localNotification:
public class GeofenceListenerImpl implements GeofenceListener {
#Override
public void onExit(String id) {
}
#Override
public void onEntered(String id) {
if(Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
Dialog.show("Welcome", "Thanks for arriving", "OK", null);
});
} else {
LocalNotification ln = new LocalNotification();
ln.setId("LnMessage");
ln.setAlertTitle("Welcome");
ln.setAlertBody("Thanks for arriving!");
Display.getInstance().scheduleLocalNotification(ln, 10, LocalNotification.REPEAT_NONE);
}
}
}
Why the following doesnot work? (it only work when the app is running or is minimized but not when it is destroyed.)
public class GeofenceListenerImpl implements GeofenceListener {
#Override
public void onExit(String id) {
System.out.println("geofence onExit");
}
#Override
public void onEntered(String id) {
if(Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
System.out.println("geofence isMinimized");
});
} else {
System.out.println("geofence when app is closed");
//I want to run connectionRequest here but is not working
}
}
}
PS. I've used background fetch but it only works when the app is minimized.
Update1: Demo of how I used connectionRequest outside of minimized() method...
public class GeofenceListenerImpl implements GeofenceListener {
#Override
public void onExit(String id) {
System.out.println("geofence onExit");
}
#Override
public void onEntered(String id) {
if(Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
});
} else {
System.out.println("geofence when app is closed");
Connection c = new Connection();
c.liveTrackConnectionMethod("22" , "23");
}
}
}
Connection class
public class Connection {
ArrayList<Map<String, Object>> response;
public void liveTrackConnectionMethod(String lat, String lon) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map parser = jSONParser.parseJSON(new InputStreamReader(input));
response = null;
}
};
cr.setPost(true);
cr.setUrl("http://url.com");
cr.addArgument("userid", Preferences.get(AllUrls.userIdPreference, null));
cr.addArgument("lat", lat + "");
cr.addArgument("long", lon + "");
cr.addRequestHeader("Accept", "application/json");
NetworkManager.getInstance().addToQueueAndWait(cr);
}
}
I think an app will always return false for isMinimized() when the app is closed or minimized (i.e. not currently running in the foreground) I may be wrong about this.
Try calling your connectionRequest script outside the isMinimized(). After all, you will want to keep track of user location whether they are using the app or not.
Your first solution with LocalNotification will show users a notification by calling the else part, rather than the Dialog when they're using the app, because isMinimized() will be false.
IDE: NetBeans
Desktop OS Windows 10
Simulator Android/iOS
Device Android/iOS
I am able to get authentication to work with connection request. I am having to get header information and then in another part of the app, send that same information back to the cgi-bin. Below is my code and I commented on the parts where I believe I need to do something with a header and or cookie. I'm very new to this and It's been difficult finding even a basic header/cookie tutorial.
/**
* Your application code goes here<br>
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
package userclasses;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.Cookie;
import com.codename1.io.NetworkEvent;
import com.codename1.io.NetworkManager;
import com.codename1.io.Storage;
import com.codename1.notifications.LocalNotification;
import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;
import java.util.Timer;
import java.util.TimerTask;
//import org.apache.commons.httpclient.UsernamePasswordCredentials;
//import org.apache.commons.httpclient.auth.AuthScope;
/**
*
* #John Barrett
*/
public class StateMachine extends StateMachineBase {
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class members there,
// the constructor might be invoked too late due to race conditions that might occur
}
/**
* this method should be used to initialize variables instead of
* the constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
}
boolean stop = false;
boolean notify = false;
String OnOff;
#Override // Starts monitor action.
protected void onMain_ButtonAction(Component c, ActionEvent event){
// starts a timer to repeat monitor every minute.
Timer timer = new Timer();
String text = (String) Storage.getInstance().readObject("SavedData");
timer.schedule( new TimerTask(){
#Override
public void run(){
if (stop == true){
cancel();//Monitor ends
}
//Starts a connection with the URL to monitor
ConnectionRequest r = new ConnectionRequest();
r.setUrl("http://vault.infinitevault.com/cgi-bin/absentmedia?customer=" + text.toLowerCase().trim());
r.setPost(true);
// Post Header/Cookie information to URL for access NEED HELP WITH THIS!
r.setHttpMethod("HEAD");
r.setContentType("text/xml");
r.setCookiesEnabled(true);
findCodeLabel(c).setText("Monitoring: " + text.toUpperCase());
r.addResponseListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev){
// Monitor starts
try{
NetworkEvent event = (NetworkEvent) ev;
// Need to post header/cookie information here? HELP!
Cookie.isAutoStored();
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
boolean none;
none = decodedData.endsWith("NONE\n");
if (!none){
System.out.println(decodedData);
findCodeTextArea(c).setText(decodedData);
LocalNotification n = new LocalNotification();
n.setId("OSStorage");
n.setAlertBody(decodedData);
n.setAlertTitle("Absent Media");
Display.getInstance().scheduleLocalNotification(
n,
System.currentTimeMillis() + 10 * 1000, // fire date/time
LocalNotification.REPEAT_MINUTE // Whether to repeat and what frequency
);
if (notify != true){
Display.getInstance().vibrate(5000);
}
Storage.getInstance().writeObject("MonitorData", decodedData);
}
else{
System.out.println("None");
findCodeTextArea(c).setText("System is Good");
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
NetworkManager.getInstance().addToQueue(r);
}
}, 0, 60*1000);
}
#Override // Stops the monitoring action.
protected void onMain_StopButtonAction(Component c, ActionEvent event) {
super.onMain_StopButtonAction(c, event);//To change body of generated methods, choose Tools | Templates.
stop = true;
findCodeLabel(c).setText("Monitor Stopped");
findCodeTextArea(c).setText("");
findCodeTextArea(c).setHint("System information will show here");
Storage.getInstance().deleteStorageFile("MonitorData");
}
#Override // Saves the settings to storage.
protected void onSettings_SetSaveAction(Component c, ActionEvent event) {
String Station = findSetStation(c).getText();
Storage.getInstance().writeObject("SavedData", Station);
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findStationLabel(c).setText("Saved Station is " + LoadStation);
}
#Override // Sets what is saved to appear when in settings.
protected void beforeSettings(Form f) {
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findStationLabel(f).setText("Saved Station is " + LoadStation);
findSetStation(f).setText(LoadStation);
String CurrentNotify = (String) Storage.getInstance().readObject("OnOff");
findSetNotifyLabel(f).setText("Vibration is " + CurrentNotify);
}
#Override // Sets what is saved to appear when in monitor screen.
protected void beforeMain(Form f) {
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findCodeLabel(f).setText(LoadStation);
if (findCodeTextArea(f) != null){
String foundData = (String) Storage.getInstance().readObject("MonitorData");
findCodeTextArea(f).setText(foundData);
}
}
#Override // Sets notification for turning vibration on.
protected void onSettings_SetNotifyOnAction(Component c, ActionEvent event) {
notify = false;
OnOff = "ON";
Storage.getInstance().writeObject("NotifyOn", notify);
Storage.getInstance().writeObject("OnOff", OnOff);
findSetNotifyLabel(c).setText("Vibration is " + OnOff);
}
#Override // Sets notification for turning vibration off.
protected void onSettings_SetNotifyOffAction(Component c, ActionEvent event) {
notify = true;
OnOff = "OFF";
Storage.getInstance().writeObject("NotifyOn", notify);
Storage.getInstance().writeObject("OnOff", OnOff);
findSetNotifyLabel(c).setText("Vibration is " + OnOff);
}
#Override // Sets message for monitoring or not.
protected void beforeStartPage(Form f) {
Storage.getInstance().deleteStorageFile("MonitorData");
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
}
#Override // Login button pressed after entering username and password.
protected void onLogin_LoginAction(Component c, ActionEvent event) {
// Gets the username and password entered.
String userName = findUsename().getText();
String passWord = findPassword().getText();
// Establishes a conneciton to authentication.
ConnectionRequest req=new ConnectionRequest();
req.setPost(false);
req.setUrl("http://authentication.infinitevault.com/validate.php");
req.addArgument("username",userName);
req.addArgument("password",passWord);
req.addArgument("grant_type","client_credentials");
// To get the Header/Cookie information.
req.getHttpMethod();
req.setCookiesEnabled(true);
Cookie.setAutoStored(true);
Cookie.isAutoStored();
// Sends message to user that system is verifying.
findDenied(c).setText("Verifying");
NetworkManager.getInstance().addToQueueAndWait(req);
if (req.getResponseData() != null) {
String token = new String(req.getResponseData());
token = token.substring(token.indexOf('=') + 1);
System.out.println(token);
// Checks credentials if response is denied, goes back,
// If response is authenticated goes to main monitor form.
if (token.endsWith("denied")){
/*try {
Thread.sleep(2000); //1000 milliseconds is one second.
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}*/
back();
}
else {
showForm("Main",null);
}
}
}
}//end of app
Just override the connection request method cookieReceived(Cookie c) and handle the logic of each cookie there.
I have download and use the code form the following URL
https://github.com/Pmovil/Toast to display toast message.
Initially I got NativeToastImpl Not implemented error. I have resolved by coping the native related code to my project. Now the System throws Runtime Exception "Toast is not supported in this platform."
Here is my code to display toast message.
public class MyApplication {
private Form current;
private static Object context;
public void init(Object context) {
MyApplication.context = context;
}
public static Object getContext() {
return context;
}
public void start() {
if (current != null) {
current.show();
return;
}
showLoginForm();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
private void showLoginForm() {
Form form = new Form("WelCome ...");
Button b = new Button(" Login ");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Log.p(" *** " + MyApplication.getContext());
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG);
}
});
form.addComponent(b);
form.show();
}}
I have used Net Beans IDE for development, OS : windows 8.1
Please let me know I am doing wrong in this code and
Is there any other way to display toast messages using codename one?.
Thanks in advance
please edit the following code and please test the toast in device . Toast is not available in emulator.
public void init(Object context) {
this.context = context;
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Toast.makeText(context, "HI", Toast.LENGTH_LONG);
}
});
You missed the show() method on Toast.
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG).show();