getRunningAppProcesses() does not return launcher package("com.android.launcher") in Lollipop 5.1.1 - android-5.1.1-lollipop

I am using the below code for getting current processes running on top. But it did not return launcher package("com.android.launcher") when i am in home screen of the device.
ActivityManager manager = (ActivityManager) this
.getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> processes = manager
.getRunningAppProcesses();
for (RunningAppProcessInfo process : processes) {
if ((process.pkgList[0].equalsIgnoreCase("com.android.launcher"))
|| (process.pkgList[0]
.equalsIgnoreCase("com.google.android.googlequicksearchbox"))
)) {
return true;
} else {
return false;
}
}

Related

Xamarin iOS - Handling Geofence intersection triggers after terminating an app

I am trying to handle geofence intersection triggers when my app is terminated (not background). I want handle the enter/exit triggers from CLLocationManager even if my app is not running. It should wake up my app at the background, do the required processing on enter/exit.
To do this, a lot of places its given that it is possible using background app refresh functionality. I have the following code written but as soon as i terminate the application, it stops hearing the geofence trigger events.
Can anybody please guide me how to handle these events even if application is terminated ?
public async Task StartLocationUpdates()
{
_cts = new CancellationTokenSource();
_taskId = UIApplication.SharedApplication.BeginBackgroundTask("LongRunningTask", OnExpiration);
try
{
if (CLLocationManager.LocationServicesEnabled)
{
LocMgr.DesiredAccuracy = 1;
LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
{
var locations = e.Locations;
};
LocMgr.StartUpdatingLocation();
if (CLLocationManager.LocationServicesEnabled)
{
if (CLLocationManager.Status != CLAuthorizationStatus.Denied)
{
if (CLLocationManager.IsMonitoringAvailable(typeof(CLCircularRegion)))
{
LocMgr.DidStartMonitoringForRegion += (o, e) =>
{
Console.WriteLine("Now monitoring region {0}", e.Region.ToString());
};
LocMgr.RegionEntered += (o, e) =>
{
Instance.Speak("Just entered " + e.Region.ToString());
};
LocMgr.RegionLeft += (o, e) =>
{
Instance.Speak("Just left " + e.Region.ToString());
};
foreach (CLCircularRegion region in RegionList)
{
if (region != null)
{
StopMonitoringRegion(region);
}
LocMgr.StartMonitoring(region);
}
}
else
{
Console.WriteLine("This app requires region monitoring, which is unavailable on this device");
}
LocMgr.Failed += (o, e) =>
{
Console.WriteLine(e.Error);
};
}
else
{
Console.WriteLine("App is not authorized to use location data");
}
}
else
{
Console.WriteLine("Location services not enabled, please enable this in your Settings");
}
}
}
catch (OperationCanceledException)
{
}
}
Thank You in advance.
It seems you have added the privacy keys in the info.plist to enable the location service. If you want to enable it when the app is on background state or terminated, we also should turn on the Background Modes: Capabilities > Background Modes > Location updates.
Then we can initialize the location manager in AppDelegate:
CLLocationManager locationManager;
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
locationManager = new CLLocationManager();
locationManager.Delegate = new MyLocationDelegate();
//enable service when app is on background or terminated
locationManager.PausesLocationUpdatesAutomatically = false;
locationManager.AllowsBackgroundLocationUpdates = true;
locationManager.RequestAlwaysAuthorization();
locationManager.DistanceFilter = 100.0;
locationManager.DesiredAccuracy = 1;
// The important request can awake your app
locationManager.StartMonitoringSignificantLocationChanges();
locationManager.StartUpdatingLocation();
return true;
}
The event LocationsUpdated() will also fire if your location has been changed even your app has been terminated:
public class MyLocationDelegate : CLLocationManagerDelegate
{
public override void LocationsUpdated(CLLocationManager manager, CLLocation[] locations)
{
//Handle your method here
}
}
You can test this with your simulator: Debug > Location > Freeway Drive. Store the locations to your sandbox folder in the event above. Force quit your app, after a few seconds open it, retrieve the file you stored. You will find the whole locations records.

I need to manipulate focus shifting

This is the scenario I want:
I'm checking for the presence of an application (using protocol detection), if it's not present the exe file automatically starts downloading. The webpage continuously checks in regular interval whether the app has been successfully downloaded and when the installation is complete, the browser prompts to open the app.
What is working:
The download is starting automatically. The webpage is checking for the presence of the app in regular interval.
What is NOT working:
After the exe is downloaded, when I start the download, the focus shifts and the webpage thinks that the app has been launched, whereas the app actually hasn't yet been installed even.
I need a focus checking mechanism which detects when the specific app has been launched and focus shifts and not respond to any other focus shifts.
This is my code:
_registerEvent = function(target, eventType, cb) {
if (target.addEventListener) {
target.addEventListener(eventType, cb);
return {
remove: function() {
target.removeEventListener(eventType, cb);
}
};
} else {
target.attachEvent(eventType, cb);
return {
remove: function() {
target.detachEvent(eventType, cb);
}
};
}
},
checkIfHasProtocol = function($el) {
openUriWithTimeoutHack(url);
},
openUriWithTimeoutHack = function(protocol) {
var timeout = setTimeout(function() {
handler.remove();
checkIfHasProtocol(protocol);
}, 5000);
var target = window;
while (target != target.parent) {
target = target.parent;
}
var handler = _registerEvent(window, "blur", onBlur);
function onBlur() {
if (tabVisible() && isBlurred) {
clearTimeout(timeout);
handler.remove();
//App has been launched
}
}
}
window.location = protocol;
};
tabVisible(function() {
if (tabVisible() && inCheck) {
inCheck = false;
}
});
window.addEventListener("blur", function() {
isBlurred = true;
});
window.addEventListener("focus", function() {
isBlurred = false;
inCheck = false;
});

restore in-app purchases not working properly

I'm using Flash CS6 to build apps for iOS and Android.
I have built 6 working apps and in-app purchases and restoring was working properly. Now, I'm building my 7th app and I tested my in-app purchases. Purchasing works very well but when I remove the app and re-install and come to buy a product. It tells that I have already purchases the product and it will restore it for free, but it keeps loading and nothing happens.
This happened for all old apps as well.
*Note: I publish the SWF using Flash then I build the IPA using cmd
I use this as3 code:
function log(s:String):void
{
trace(s);
log_txt.text = s;
}
function initStorekit():void
{
log("initializing StoreKit..");
if (! StoreKit.isSupported())
{
log("Store Kit iOS purchases is not supported on this platform.");
return;
}
else
{
supported = true;
}
StoreKit.create();
log("StoreKit Initialized.");
// make sure that purchases will actually work on this device before continuing!
// (for example, parental controls may be preventing them.)
if (! StoreKit.storeKit.isStoreKitAvailable())
{
log("Store is disabled on this device.");
return;
}
// add listeners here
StoreKit.storeKit.addEventListener(StoreKitEvent.PRODUCT_DETAILS_LOADED,onProductsLoaded);
StoreKit.storeKit.addEventListener(StoreKitEvent.PURCHASE_SUCCEEDED,onPurchaseSuccess);
StoreKit.storeKit.addEventListener(StoreKitEvent.PURCHASE_CANCELLED,onPurchaseUserCancelled);
StoreKit.storeKit.addEventListener(StoreKitEvent.TRANSACTIONS_RESTORED, onTransactionsRestored);
// adding error events. always listen for these to avoid your program failing.;
StoreKit.storeKit.addEventListener(StoreKitErrorEvent.PRODUCT_DETAILS_FAILED,onProductDetailsFailed);
StoreKit.storeKit.addEventListener(StoreKitErrorEvent.PURCHASE_FAILED,onPurchaseFailed);
StoreKit.storeKit.addEventListener(StoreKitErrorEvent.TRANSACTION_RESTORE_FAILED, onTransactionRestoreFailed);
// initialize a sharedobject that's holding our inventory.;
initSharedObject();
var productIdList:Vector.<String>=new Vector.<String>();
productIdList.push(LEVELPACK1_ID);
productIdList.push(LEVELPACK2_ID);
productIdList.push(LEVELPACK3_ID);
productIdList.push(REMOVEADS_ID);
productIdList.push(ALLINPACKAGE_ID);
// when this is done, we'll get a PRODUCT_DETAILS_LOADED or PRODUCT_DETAILS_FAILED event and go on from there...;
log("Loading product details...");
StoreKit.storeKit.loadProductDetails(productIdList);
}
function onProductsLoaded(e:StoreKitEvent):void
{
log("products loaded.");
for each (var product:StoreKitProduct in e.validProducts)
{
trace("ID: "+product.productId);
trace("Title: "+product.title);
trace("Description: "+product.description);
trace("String Price: "+product.localizedPrice);
trace("Price: "+product.price);
}
log("Loaded "+e.validProducts.length+" Products.");
// if any of the product ids we tried to pass in were not found on the server,
// we won't be able to by them so something is wrong.
if (e.invalidProductIds.length > 0)
{
log("[ERR]: these products not valid:"+e.invalidProductIds.join(","));
return;
}
}
function onProductDetailsFailed(e:StoreKitErrorEvent):void
{
log("ERR loading products:"+e.text);
}
function initSharedObject():void
{
this.sharedObject = SharedObject.getLocal("myPurchases");
// check if the application has been loaded before. if not, create a store of our purchases in the sharedobject.
if (sharedObject.data["inventory"] == null)
{
sharedObject.data["inventory"]=new Object();
}
updateInventoryMessage();
}
/** Update Inventory Message */
function updateInventoryMessage():void
{
var inventory:Object = sharedObject.data["inventory"];
// if the value is set to something, you have it
if (inventory[LEVELPACK1_ID] != null)
{
unlockLP1_fnc();
}
if (inventory[LEVELPACK2_ID] != null)
{
unlockLP2_fnc();
}
if (inventory[LEVELPACK3_ID] != null)
{
unlockLP3_fnc();
}
if (inventory[REMOVEADS_ID] != null)
{
hideAds_fnc();
}
if (inventory[ALLINPACKAGE_ID] != null)
{
unlockLP1_fnc();unlockLP2_fnc();unlockLP3_fnc();hideAds_fnc();
}
log("Has hasUnlocked? ");
}
function purchaseUnlock(s:String):void
{
enableLoading();
// for this to work, you must have added the value of LEVELPACK_PRODUCT_ID in the iTunes Connect website
log("start purchase of non-consumable '"+s+"'...");
// we won't let you purchase it if its already in your inventory!
var inventory:Object = sharedObject.data["inventory"];
if (inventory[s] != null)
{
log("You already have unlocked this!");
return;
}
StoreKit.storeKit.purchaseProduct(s);
}
/** Example of how to restore transactions */
function restoreTransactions():void
{
enableLoading();
log("requesting transaction restore...");
StoreKit.storeKit.restoreTransactions();
}
function onPurchaseSuccess(e:StoreKitEvent):void
{
log("Successful purchase of '"+e.productId+"'");
disableLoading();
// update our sharedobject with the state of this inventory item.
// this is just an example to make the process clear. you will
// want to make your own inventory manager class to handle these
// types of things.
var inventory:Object = sharedObject.data["inventory"];
switch (e.productId)
{
case ALLINPACKAGE_ID :
inventory[ALLINPACKAGE_ID] = "purchased";
break;
case LEVELPACK1_ID :
inventory[LEVELPACK1_ID] = "purchased";
break;
case LEVELPACK2_ID :
inventory[LEVELPACK2_ID] = "purchased";
gotoAndStop("lvls");
break;
case LEVELPACK3_ID :
inventory[LEVELPACK3_ID] = "purchased";
gotoAndStop("lvls");
break;
case REMOVEADS_ID :
inventory[REMOVEADS_ID] = "purchased";
gotoAndStop("mm");
break;
default :
log("xxxxx");
// we don't do anything for unknown items.
}
// save state!
sharedObject.flush();
// update the message on screen;
updateInventoryMessage();
}
function onPurchaseFailed(e:StoreKitErrorEvent):void
{
disableLoading();
log("FAILED purchase="+e.productId+",t="+e.transactionId+",o="+e.originalTransactionId);
}
function onPurchaseUserCancelled(e:StoreKitEvent):void
{
disableLoading();
log("CANCELLED purchase="+e.productId+","+e.transactionId);
}
function onTransactionsRestored(e:StoreKitEvent):void
{
disableLoading();
log("All previous transactions restored!");
var inventory:Object = sharedObject.data["inventory"];
switch (e.productId)
{
case ALLINPACKAGE_ID :
inventory[ALLINPACKAGE_ID] = "purchased";
break;
case LEVELPACK1_ID :
inventory[LEVELPACK1_ID] = "purchased";
break;
case LEVELPACK2_ID :
inventory[LEVELPACK2_ID] = "purchased";
gotoAndStop("lvls");
break;
case LEVELPACK3_ID :
inventory[LEVELPACK3_ID] = "purchased";
gotoAndStop("lvls");
break;
case REMOVEADS_ID :
inventory[REMOVEADS_ID] = "purchased";
gotoAndStop("mm");
break;
default :
log("xxxxx");
// we don't do anything for unknown items.
}
// save state!
sharedObject.flush();
updateInventoryMessage();
}
function onTransactionRestoreFailed(e:StoreKitErrorEvent):void
{
disableLoading();
log("an error occurred in restore purchases:"+e.text);
}

How to implement image swipe for Blackberry 5.0 and later OS devices?

I need to develop swipe functionality in an application. For that, i have added five bitmapfields in five different verticalfield managers and these five verticalfield managers have been added in a horizontalfield manager with Horizontal Scroll property and then I tried to implement swipe functionality using Touch Event. Below code is working for Blackberry 5.0 OS devices but its not working in Blackberry 6.0 and later OS devices.
protected boolean touchEvent(TouchEvent message)
{
try{
int x = message.getX(1);
int y = message.getY(1);
int eventCode = message.getEvent();
if(eventCode == TouchEvent.DOWN)
{
Dx=x;
Dy=y;
}
else if(eventCode == TouchEvent.UP)
{
Ux=x;
Uy=y;
disX= Dx-Ux;
disY= Dy-Uy;
if(disX > (Display.getWidth()/3) && this.index<6)
{
if(this.index<5)
this.index++;
vfmImage[this.index].setFocus();
System.out.println("disX :"+disX +" differnt :"+(Display.getWidth()/3)+" Index :"+this.index);
}
else if(disX < Display.getWidth() -(Display.getWidth() + Display.getWidth()/3) && index>0)
{
if(this.index>0)
this.index--;
vfmImage[this.index].setFocus();
System.out.println("disX :"+disX +"differnt :"+(Display.getWidth() -(Display.getWidth() + Display.getWidth()/3))+" Index :"+this.index);
}
else
{
if(index==0)
{
vfmImage[1].setFocus();
}
else
{
vfmImage[this.index-1].setFocus();
}
vfmImage[this.index].setFocus();
}
}
}
catch (Exception e)
{
Dialog.alert("catch");
e.printStackTrace();
}
return super.touchEvent(message);
}
Thanks
Devang

iOS UIAutomation UIAElement.isVisible() throwing stale response?

I'm trying to use isVisible() within a loop to create a waitForElement type of a function for my iOS UIAutomation. When I try to use the following code, it fails while waiting for an element when a new screen pops up. The element is clearly there because if I do a delay(2) before tapping the element it works perfectly fine. How is everyone else accomplishing this, because I am at a loss...
Here's the waitForElement code that I am using:
function waitForElement(element, timeout, step) {
if (step == null) {
step = 0.5;
}
if (timeout == null) {
timeout = 10;
}
var stop = timeout/step;
for (var i = 0; i < stop; i++) {
if (element.isVisible()) {
return;
}
target.delay(step);
}
element.logElement();
throw("Not visible");
}
Here is a simple wait_for_element method that could be used:
this.wait_for_element = function(element, preDelay) {
if (!preDelay) {
target.delay(0);
}
else {
target.delay(preDelay);
}
var found = false;
var counter = 0;
while ((!found) && (counter < 60)) {
if (!element.isValid()) {
target.delay(0.5);
counter++;
}
else {
found = true;
target.delay(1);
}
}
}
I tend to stay away from my wait_for_element and look for any activityIndicator objects on screen. I use this method to actual wait for the page to load.
this.wait_for_page_load = function(preDelay) {
if (!preDelay) {
target.delay(0);
}
else {
target.delay(preDelay);
}
var done = false;
var counter = 0;
while ((!done) && (counter < 60)) {
var progressIndicator = UIATarget.localTarget().frontMostApp().windows()[0].activityIndicators()[0];
if (progressIndicator != "[object UIAElementNil]") {
target.delay(0.25);
counter++;
}
else {
done = true;
}
}
target.delay(0.25);
}
Here is a simple and better one using recursion. "return true" is not needed but incase u want it.
waitForElementToDismiss:function(elementToWait,waitTime){ //Using recursion to wait for an element. pass in 0 for waitTime
if(elementToWait && elementToWait.isValid() && elementToWait.isVisible() && (waitTime < 30)){
this.log("Waiting for element to invisible");
target.delay(1);
this.waitForElementToDismiss(elementToWait, waitTime++);
}
if(waitTime >=30){
fail("Possible login failed or too long to login. Took more than "+waitTime +" seconds")
}
return true;
}
Solution
I know this is an old question but here is my solution for a situation where I have to perform a repetitive task against a variable timed event. Since UIAutomation runs on javascript I use a recursive function with an empty while loop that checks the critical control state required before proceeding to the next screen. This way one never has to hard code a delay.
// Local target is the running simulator
var target = UIATarget.localTarget();
// Get the frontmost app running in the target
var app = target.frontMostApp();
// Grab the main window of the application
var window = app.mainWindow();
//Get the array of images on the screen
var allImages = window.images();
var helpButton = window.buttons()[0];
var nextButton = window.buttons()[2];
doSomething();
function doSomething ()
{
//only need to tap button for half the items in array
for (var i=0; i<(allImages.length/2); i++){
helpButton.tap();
}
//loop while my control is NOT enabled
while (!nextButton.isEnabled())
{
//wait
}
//proceed to next screen
nextButton.tap();
//go again
doSomething();
}

Resources