Which event tells you that the device is successfully started - blackberry

I am making an application that auto starts when the phone restarts. I want to run some events when the phone complets its restart. The UiApp is running even before the device finishes his reset cause I configured the app as an auto start app.
What event should I listen too and that starts when the phone completes the reboot, not in between?
Thanks

It is possible to know if the system is in startup by using :
ApplicationManager.isStartup()
You will need to poll this using a timer till it returns false. However it must be borne in mind that this means that the OS has booted and the system is able to run the application. It does not mean that the entire environment for your application to run is set up completely. For example (as noted by Michael) microSD card might not have been mounted, network connectivity might not been established, or some other service on which your application might depend is not yet available. It's up to you to verify they are available before you begin working of your application.
The approach you need to take is:
Poll if isStartup returns false (System is not in startup phase)
Implement FileSystemListener to check if microSD card is mounted.
Note that mount name for a microSD card is "SDCard".
class FileSystemListenerImpl implements FileSystemListener
{
final static String SDCARD_NAME ="SDCard/";
public FileSystemListenerImpl( )
{
}
public void rootChanged( int state, String rootName )
{
if( state == FileSystemListener.ROOT_ADDED)
{
if( SDCARD_NAME.equals(rootName))
{
_isMicroSDReady=true;
scheduleApplicationStart();
removeFileSystemListener(this);
}
}
else if( state == FileSystemListener.ROOT_REMOVED)
{
}
}
}

Related

How to disable vpn connection when app is terminated in iOS?

I'm implementing Personal VPN by PacketTunnel. Through startVPNTunnel method of NETunnelProviderManager, i checked whether VPN Connection is run well.
However, I have a problem. I added the exit code of vpn connection in applicationWillTerminate to disable vpn connection when app is terminated like following code below. But it doesn't work.
If test this code, loadAllFromPreferences is run but callback function of loadAllFromPreferences isn't called. This code runs well anywhere except applicationWillTerminate. Why it doesn't work? Is there any way to disable vpn when app is terminated?
func applicationWillTerminate(_ application: UIApplication) {
NETunnelProviderManager.loadAllFromPreferences { (managers, error) in
var manager:NETunnelProviderManager?=nil;
for m in managers! {
if m != nil {
if m.localizedDescription == "profile" {
manager = m;
break
}
}
}
manager?.connection.stopVPNTunnel()
}
}
As per Apple's documentation of applicationWillTerminate(application:):
Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.
If applicationWillTerminate is called but the closure is not make sure that it does not take more than "approximately" (sic) 5 seconds.
I have not used the libraries you are using but from a general point of view there are probably better strategies than iterating over all available managers. Like storing a reference/identifier to a given manager when starting a connection and using that reference/identifier to terminate it.

ReactJs PWA not updating on iOS

I'm building a ReactJs PWA but I'm having trouble detecting updates on iOS.
On Android everything is working great so I'm wondering if all of this is related to iOS support for PWAs or if my implementation of the service worker is not good.
Here's what I've done so far:
Build process and hosting
My app is built using webpack and hosted on AWS. Most of the files (js/css) are built with some hash in their name, generated from their content. For those which aren't (app manifest, index.html, sw.js), I made sure that AWS serves them with some Cache-Control headers preventing any cache. Everything is served over https.
Service Worker
I kept this one as simple as possible : I didn't add any cache rules except precache for my app-shell:
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);
Service-worker registration
Registration of the service worker occurs in the main ReactJs App component, in the componentDidMount() lifecycle hook:
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
reg.onupdatefound = () => {
this.newWorker = reg.installing;
this.newWorker.onstatechange = () => {
if (this.newWorker.state === 'installed') {
if (reg.active) {
// a version of the SW is already up and running
/*
code omitted: displays a snackbar to the user to manually trigger
activation of the new SW. This will be done by calling skipWaiting()
then reloading the page
*/
} else {
// first service worker registration, do nothing
}
}
};
};
});
}
}
Service worker lifecycle management
According to the Google documentation about service workers, a new version of the service worker should be detected when navigating to an in-scope page. But as a single-page application, there is no hard navigation happening once the app has been loaded.
The workaround I found for this is to hook into react-router and listen for route changes, then manually ask the registered service worker to update itself :
const history = createBrowserHistory(); // from 'history' node package
history.listen(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.getRegistration()
.then((reg) => {
if (!reg) {
return null;
}
reg.update();
});
}
});
Actual behavior
Throwing a bunch of alert() everywhere in the code showed above, this is what I observe :
When opening the pwa for the first time after adding it to the homescreen, the service worker is registered as expected, on Android and iOS
While keeping the app opened, I deploy a new version on AWS. Navigating in the app triggers the manual update thanks to my history listener. The new version is found, installed in the background. Then my snackbar is displayed and I can trigger the switch to the new SW.
Now I close the app and deploy a new version on AWS. When opening the app again :
On Android the update is found immediately as Android reloads the page
iOS does not, so I need to navigate within the app for my history listener to trigger the search for an update. When doing so, the update is found
After this, for both OS, my snackbar is displayed and I can trigger the switch to the new SW
Now I close the app and turn off the phones. After deploying a new version, I start them again and open the app :
On Android, just like before, the page is reloaded which detects the update, then the snackbar is displayed, etc..
On iOS, I navigate within the app and my listener triggers the search for an update. But this time, the new version is never found and my onupdatefound event handler is never triggered
Reading this post on Medium from Maximiliano Firtman, it seems that iOS 12.2 has brought a new lifecycle for PWAs. According to him, when the app stays idle for a long time or during a reboot of the device, the app state is killed, as well as the page.
I'm wondering if this could be the root cause of my problem here, but I was not able to find anyone having the same trouble so far.
So after a lot of digging and investigation, I finally found out what was my problem.
From what I was able to observe, I think there is a little difference in the way Android and iOS handle PWAs lifecycle, as well as service workers.
On Android, when starting the app after a reboot, it looks like starting the app and searching an update of the service worker (thanks to the hard navigation occuring when reloading the page) are 2 tasks done in parallel. By doing that, the app have enough time to subscribe to the already existing service worker and define a onupdatefound() handler before the new version of the service worker is found.
On the other hand with iOS, it seems that when you start the app after a reboot of the device (or after not using it for a long period, see Medium article linked in the main topic), iOS triggers the search for an update before starting your app. And if an update is found, it will be installed and and enter its 'waiting' status before the app is actually started. This is probably what happens when the splashscreen is displayed...
So in the end, when your app finally starts and you subscribe to the already existing service worker to define your onupdatefound() handler, the update has already been installed and is waiting to take control of the clients.
So here is my final code to register the service worker :
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
if (reg.waiting) {
// a new version is already waiting to take control
this.newWorker = reg.waiting;
/*
code omitted: displays a snackbar to the user to manually trigger
activation of the new SW. This will be done by calling skipWaiting()
then reloading the page
*/
}
// handler for updates occuring while the app is running, either actively or in the background
reg.onupdatefound = () => {
this.newWorker = reg.installing;
this.newWorker.onstatechange = () => {
if (this.newWorker.state === 'installed') {
if (reg.active) {
// a version of the SW already has control over the app
/*
same code omitted
*/
} else {
// very first service worker registration, do nothing
}
}
};
};
});
}
}
Note :
I also got rid of my listener on history that I used to trigger the search for an update on every route change, as it seemed overkill.
Now I rely on the Page Visibility API to trigger this search every time the app gets the focus :
// this function is called in the service worker registration promise, providing the ServiceWorkerRegistration instance
const registerPwaOpeningHandler = (reg) => {
let hidden;
let visibilityChange;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
window.document.addEventListener(visibilityChange, () => {
if (!document[hidden]) {
// manually force detection of a potential update when the pwa is opened
reg.update();
}
});
return reg;
};
As noted by Speckles (thanks for saving me the headache), iOS installs the new SW before launching the app. So the SW doesn't get a chance to catch the 'installing' state.
Work-around: check if the registration is in the waiting state then handle it.
I've made an (untested) example of handling this. - a mod to the default CRA SW.

How to keep .NET Core console app alive in Docker container

I am testing a .NET Core 2.0 app which uses the Service Bus SDK to retrieve messages from an Event Hub. I setup a console app to do that, and intend to run the app as a Docker container.
This method creates the Event Host Processor which will read the messages:
private static async Task MainAsync(string[] args)
{
Console.WriteLine("Registering EventProcessor...");
var eventProcessorHost = new EventProcessorHost(
EhEntityPath,
PartitionReceiver.DefaultConsumerGroupName,
EhConnectionString,
StorageConnectionString,
StorageContainerName);
// Registers the Event Processor Host and starts receiving messages
Console.WriteLine("Retrieving messages");
await eventProcessorHost.RegisterEventProcessorAsync<EventProcessor>();
Console.WriteLine("Sleeping");
Thread.Sleep(Timeout.Infinite);
}
As the event processor implemented in class EventProcessor will be the one handling the events, I am trying to prevent the console app to exit when the registration of the Processor is finished.
However, I can't find a reliable way to keep the app alive. If I run this container as-is, all I see in the output window is:
Registering EventProcessor...
Retrieving messages
Sleeping
and no messages are ever received.
Thanks all for the suggestions.
I followed those articles but eventually ended up with this, which applies specifically to .NET Core apps:
https://github.com/aspnet/Hosting/issues/870
I've tested it and the app can shutdown gracefully when it receives a termination signal from the Docker runtime.
UPDATE: this is the relevant sample from the GH issue link above:
public class Program
{
public static void Main(string[] args)
{
var ended = new ManualResetEventSlim();
var starting = new ManualResetEventSlim();
AssemblyLoadContext.Default.Unloading += ctx =>
{
System.Console.WriteLine("Unloding fired");
starting.Set();
System.Console.WriteLine("Waiting for completion");
ended.Wait();
};
System.Console.WriteLine("Waiting for signals");
starting.Wait();
System.Console.WriteLine("Received signal gracefully shutting down");
Thread.Sleep(5000);
ended.Set();
}
}

Reset app state between InstrumentationTestCase runs

One of my QA engineers is supporting an app with a fairly large codebase and a lot of different SharedPreferences files. He came to me the other day asking how to reset the application state between test runs, as if it had been uninstalled-reinstalled.
It doesn't look like that's supported by Espresso (which he is using) nor by the Android test framework natively, so I'm not sure what to tell him. Having a native method to clear all the different SharedPreferences files would be a pretty brittle solution.
How can one reset the application state during instrumentation?
Current espresso doesn't provide any mechanism to reset application state. But for each aspect (pref, db, files, permissions) exist a solution.
Initial you must avoid that espresso starts your activity automatically so you have enough time to reset.
#Rule
public ActivityTestRule<Activity> activityTestRule = new ActivityTestRule<>(Activity.class, false, false);
And later start your activity with
activityTestRule.launchActivity(null)
For reseting preferences you can use following snippet (before starting your activity)
File root = InstrumentationRegistry.getTargetContext().getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
InstrumentationRegistry.getTargetContext().getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}
You can reset preferences after starting your activity too. But then the activity may have already read the preferences.
Your application class is only started once and already started before you can reset preferences.
I have started to write an library which should make testing more simple with espresso and uiautomator. This includes tooling for reseting application data. https://github.com/nenick/espresso-macchiato See for example EspAppDataTool with the methods for clearing preferences, databases, cached files and stored files.
Improving on #nenick's solution, encapsulate the state clearing behavior in a custom ActivityTestRule. If you do this, you can allow the test to continue to launch the activity automatically without intervention from you. With a custom ActivityTestRule, the activity is already in the desired state when it launches for the test.
Rules are particularly useful because they're not tied to any specific test class, so can be easily reused within any test class or any project.
Below is one I implemented to ensure that the app is signed out when the activity launches, per test. Some tests, when they failed, were leaving the app in a signed in state. This would then cause later tests to also fail because the later ones assumed they would need to sign in, but the app would already be signed in.
public class SignedOutActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
public SignedOutActivityTestRule(Class<T> activityClass) {
super(activityClass);
}
#Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
InstrumentationRegistry.getTargetContext()
.getSharedPreferences(
Authentication.SHARED_PREFERENCES_NAME,
Context.MODE_PRIVATE)
.edit()
.remove(Authentication.KEY_SECRET)
.remove(Authentication.KEY_USER_ID)
.apply();
}
}
you can try add this to gradle:
android {
...
defaultConfig {
...
testInstrumentationRunnerArguments clearPackageData: 'true'
}
}
refer to https://developer.android.com/training/testing/junit-runner
To remove all shared state from your device's CPU and memory after each test, use the clearPackageData flag.

detect when blackberry App is Auto-started at boot up time vs started by user

I want to have my app automatically run at start time in order to register with the HttpFilterRegistry. I know how to make my app auto-start but what I'm really after is differentiating between when the sytem starts the app and when the user starts the app. If the user is starting the app, I want to just show the GUI. If it's the system, I want to just register the HTTP filters.
Is this possible?
When you create your Alternate Entry Point, specify an "Application argument". When the app launches you can do this in your main() method
//Autostart
if( args != null && args.length > 0 && args[0].equals("the_application_argument")) {
//register HTTP filters
}
//User start
else{
//launch the GUI
}
there is a function called inStartup() in application Manager class
Determines if the device is in the process of starting up. so you can check on it.
i think its better than create new entry point and pass an arguments to main

Resources