Scenario
I have made a phonegap 1.0.0 app which loads the current location via Google Map. I have also created a plugin to display the activity indicator on the top of the screen, i.e. on the status bar of the iPhone.
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
};
function onDeviceReady()
{
//Get the plugin object
var ai = window.plugins.ActivityIndicator;
//Stop the spin, if any activity was going on earlier
ai.end();
if(navigator.geolocation) {
//Start spinning, indicating that some network activity is going on
ai.set();
navigator.geolocation.getCurrentPosition(initSearch);
}
else alert("Please try reloading");
//Stop spinning after 10 seconds
window.setTimeout(ai.end, 10000);
};
The Javascript code for the plugin is as follows:
var ActivityIndicator = function() {};
ActivityIndicator.prototype.set = function()
{
PhoneGap.exec("ActivityIndicator.start");
};
ActivityIndicator.prototype.end = function()
{
PhoneGap.exec("ActivityIndicator.end");
};
ActivityIndicator.install = function() {
if(!window.plugins)
window.plugins = {};
window.plugins.ActivityIndicator = new ActivityIndicator();
return window.plugins.ActivityIndicator;
};
PhoneGap.addConstructor(ActivityIndicator.install);
The Objective-C code for the plugin is as follows:
#import <Foundation/Foundation.h>
#ifdef PHONEGAP_FRAMEWORK
#import <PhoneGap/PGPlugin.h>
#else
#import "PGPlugin.h"
#endif
@interface ActivityIndicator : PGPlugin {}
-(void) start:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
-(void) end:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end
@implementation ActivityIndicator
- (void)start:(NSMutableArray *)arguments withDict:(NSMutableDictionary *)options
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
}
- (void)end:(NSMutableArray *)arguments withDict:(NSMutableDictionary *)options
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}
@end
Problem
As you can see in the code snippet above, I have set the Timeout for the spinning to stop after 10 seconds.
Question
How to make the activityIndicator start/stop whenever there is any network Activity?
You could’ve use notificationEx instead of doing your own, but it’s good for knowledge 🙂
Anyways, is the map calls ajax-based? If yes, and you are using jQuery, assign
.ajaxStart()and.ajaxStop()functs.I do the following:
This way, all ajax will be shown in the activity when happening.
Update:
For Zeptojs – on version 0.8 or superior ajax global implemented only on v0.8, use the following: