How to tell if GPS is enabled on Android using Titanium - android

I am working on an Android 3.2+ app in Titanium. It is crucial that I am able to determine if the device has GPS enabled. According to the Titanium API reference, Ti.Geolocation.locationServicesEnabled will always return true on Android 2.2+, because of a new "passive" location provider. Is there any other way of determining if GPS is truly enabled?
Thanks.

i think this code should work for you:
//check to see if we have GPS capabilities
if(Titanium.Geolocation.isLocationProviderEnabled(Titanium.Geolocation.PROVIDER_GPS, Titanium.Geolocation.ACCURACY_BEST) == false) {
var alertDlg = Titanium.UI.createAlertDialog({
title:'MileTrackGPS',
message:'GPS is OFF. Enable it in Settings.',
buttonNames: ['Cancel', 'Open Settings']
});
alertDlg.cancel = 0;
alertDlg.addEventListener('click', function(e){
if(!e.cancel) {
//open up the settings page
var settingsIntent = Titanium.Android.createIntent({
action: 'android.settings.LOCATION_SOURCE_SETTINGS'
});
activity.startActivity(settingsIntent);
}
else {
//close the window to exit
win.close();
}
});
alertDlg.show();
}
refrence

Alright here is an easy solution I came up with and it works well for me. I have a global variable 'timeStamp' which I initially set to zero.
Titanium.Geolocation.getCurrentPosition(function(e){
//only update fields if timer is still active
if(gpsTimer!=null)
{
//if the provider is not GPS or the timestamp is the same as the last, we do not want the results. We need to alert the user that they need to turn their GPS on.
if(e.provider['name']!="gps" || timeStamp==e.coords.timestamp)
{
//clear timeout
clearTimeout(gpsTimer);
gpsTimer = null;
//close window
get_gps_win.close();
//garbage collection
get_gps_win = null;
gpsLatField = null;
gpsLongField = null;
gpsAccuracyField = null;
timeStamp=0;
//alert user
alert("This feature is not available unless you have GPS turned on. Please turn GPS on and then try again.");
}
else
{
//update fields
gpsLatField.value=ConvertDDToDMSPlain(e.coords.latitude);
gpsLongField.value=ConvertDDToDMSPlain(e.coords.longitude);
gpsAccuracyField.value=e.coords.accuracy+" meters/"+(e.coords.accuracy*3.28084)+" feet";
gpsTimer=setTimeout(function() {
Titanium.Geolocation.fireEvent('location');
}, 1000);
}
timeStamp= e.coords.timestamp;
}
});

Related

Unity toggle to save password works flawlessly in Unity but doesn't work as expected

I have a problem with saving users login and password in PlayerPrefs. While it works very well in Unity (if the password is saved, the toggle is on on start) it doesn't work on Android (if the password is not saved, the toggle is still on on start). Before building for Android, I'm making sure that the toggle is off and password is not saved.
Here is my code:
void LoadUserPassOnStart(){
if(PlayerPrefs.HasKey("userSaved")){
if(PlayerPrefs.GetInt("userSaved") == 1){
loginEmail.text = PlayerPrefs.GetString("savedUsername");
loginPassword.text = PlayerPrefs.GetString("savedPass");
saveUserPassToggle.isOn = true;
int saved = PlayerPrefs.GetInt("userSaved");
Debug.Log(saved);
}
else if(PlayerPrefs.GetInt("userSaved") == 0)
{
saveUserPassToggle.isOn = false;
Debug.Log("Called false");
}
}
}
void SaveUserPass(Toggle saveUserPassToggle){
if(saveUserPassToggle.isOn){
PlayerPrefs.SetString("savedUsername", loginEmail.text);
PlayerPrefs.SetString("savedPass", loginPassword.text);
PlayerPrefs.SetInt("userSaved", 1);
Debug.Log("Saved");
}
else if(!saveUserPassToggle.isOn){
PlayerPrefs.SetString("savedUsername", "");
PlayerPrefs.SetString("savedPass", "");
PlayerPrefs.SetInt("userSaved", 0);
Debug.Log("Nulled");
}
}
I'm calling LoadUserPassOnStart in Start(){} and I'm adding SaveUserPass to the toggle:
saveUserPassToggle.onValueChanged.AddListener(delegate{ SaveUserPass(saveUserPassToggle);});
This issue drives me nuts, will be very grateful for suggestions.
try using PlayerPrefs.Save(); after Set the keys.
The issue was caused by the fact, that Android stores the info from PlayerPrefs even after the game is uninstalled.

How to get the phone Object in Oreo Aosp Code

I want to write Api for getdataroaming method which is already there in Aosp.
Just now I have written code like this.
ContentResolver cr=mPhone.getContext().getContentResolver();
if (Settings.Secure.getInt(cr.getContentResolver(),Settings.Secure.DATA_ROAMING) == 1) {
//Data Roaming Enabled
flag = true;
} else {
// Data Roaming Disabled
flag = false;
}
how to get the phone object in separate java file.
if I used the context.
From where i will get this context?

How to check if the location service is enabled or not in Appcelerator

Can you please help me to check if the location service is enabled or not in Appcelerator.
I am working with Titanium SDk 6.1.2 and Samsung S5 with Marshmellow OS. Even though the GPS is enabled/not in device, But every time it results in false.
Thanks in Advance.
First of all you need to check for Location Permissions for app in Android & then you need to check if location service is enabled in device or not.
Both are different statements.
First one checks for app permission to access location & 2nd is about checking location service is on or off.
Without checking Location Permissions first on Android, you cannot check for location on/off state, else it will always lead to false status.
First of all add this in tiapp.xml in ios -> plist -> dict
<key>NSLocationAlwaysUsageDescription</key>
<string>Determine Current Location</string>
Now here's the cross-compatible code for Android/iOS.
function checkLocationEnabledOrNot(_callback, _args) {
if (Titanium.Geolocation.locationServicesEnabled) {
_callback(_args);
} else {
alert("Turn on location on your device.");
}
}
// pass _callback method you want to call after successful access to location
// you can also pass arguments as 2nd parameter to the function you want to call
function startLocationProcess(_callback, _args) {
Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;
if (OS_IOS) {
checkLocationEnabledOrNot(_callback, _args);
} else if (OS_ANDROID) {
if (Ti.Geolocation.hasLocationPermissions()) {
checkLocationEnabledOrNot(_callback, _args);
} else {
Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function (locationEvent) {
if (locationEvent.success) {
checkLocationEnabledOrNot(_callback, _args);
} else {
alert("Location permissions are required to access locations.");
}
});
}
}
}
Now, on a button click whatever you want to do after location check, you can simply do it like this:
function anotherFunction(name) {
alert(name);
}
$.someButton.addEventListener('click', function (e) {
startLocationProcess(anotherFunction, "Hello D.Ish");
});

Instabug, is it possible to deactivate the shake for feedback, if there is no internet access?

I have a networkStateReceiver, that checks if I have internet or not.
If I do, I reinitiate instabug, if not, I want to deactivate. How can I do that?
I tried just setting it as null, but it doesn't work.
if(haveConnectedMobile || haveConnectedWifi){
//TODO will need to make a queue, and go through all that queue
PSLocationCenter.getInstance().initInstabug();
}else{
PSLocationCenter.getInstance().instabug = null;
}
This is my init:
public void initInstabug() {
String[] feedbackArray = getResources().getStringArray(R.array.feedback);
String randomStr = feedbackArray[new Random().nextInt(feedbackArray.length)];
Instabug.DEBUG = true;
instabug = Instabug.initialize(this)
.setAnnotationActivityClass(InstabugAnnotationActivity.class)
.setShowIntroDialog(true, PSTimelineActivity.class)
.enableEmailField(true, false)
.setEnableOverflowMenuItem(true)
.setDebugEnabled(true)
.setCommentRequired(true)
.setPostFeedbackMessage(randomStr)
.setPostBugReportMessage(randomStr) //TODO will be the post report message, random from array
.setCommentFieldHint("Please describe what went wrong")
.setPreSendingRunnable(new Runnable() {
#Override
public void run() {
String[] files = new String[2];
files[0] = Environment.getExternalStorageDirectory() + "/Passenger/passenger_log.txt";
files[1] = Environment.getExternalStorageDirectory() + "/Passenger/passenger_log2.txt";
Compress compress = new Compress(files, Environment.getExternalStorageDirectory() + "/Passenger/log.zip");
compress.zip(new CrudStateCallback() {
#Override
public void onResponse(String string) {
Log.i("", "ended making the archive");
}
});
}
})
.attachFileAtLocation(Environment.getExternalStorageDirectory() + "/Passenger/log.zip");
}
You can use this code to disable Instabug automatic invocation:
Instabug.getInstance().setInvocationEvent(IBGInvocationEvent.IBGInvocationEventNone)
This way it won't be invoked automatically. This will only affect the next Activity though (not the current one). You may force to stop and restart all listeners by calling onPause and onResume on the current Activity. (We may address that soon though, so that such changes are applied on the currently running Activity).
Don't forget to also enable the shake invocation event when internet access is restored.
Please keep in mind that Instabug SDK already caches all reports and will re-attempt to send them on next app launch until they're uploaded successfully.
Just wanted to post the updated answer.
The newer SDK has changed the name and now you can disable it by the following code:
Instabug.changeInvocationEvent(InstabugInvocationEvent.NONE)
Notice, if you want to disable it for entire application, just call this method in your Application class

When exactly is the NFC Service deactivated?

I am wondering when exactly the NFC Service is started and stopped.
The source code for android 4.0.3 seems to state that the polling is dependent on a single constant (located in NfcService.java)
/** minimum screen state that enables NFC polling (discovery) */
static final int POLLING_MODE = SCREEN_STATE_ON_UNLOCKED;
I would interpret this as "the screen light is on, therefore the nfc service is active".
BUT when the screen is locked, a NFC Tag wont be recognized, altough the screen is lit.
So I am curious: Is the NFC Service already deactivated when the lock screen appears, or is it still running but not processing the Tags?
Actually, I do not think that NFC Service is deactivated. When the screen has lower value then SCREEN_STATE_ON_UNLOCKED a device stops to ask NFC tags around. You can see this from this code:
// configure NFC-C polling
if (mScreenState >= POLLING_MODE) {
if (force || !mNfcPollingEnabled) {
Log.d(TAG, "NFC-C ON");
mNfcPollingEnabled = true;
mDeviceHost.enableDiscovery();
}
} else {
if (force || mNfcPollingEnabled) {
Log.d(TAG, "NFC-C OFF");
mNfcPollingEnabled = false;
mDeviceHost.disableDiscovery();
}
}
But NFC-EE routing is enabled util screen state is higher then SCREEN_STATE_ON_LOCKED:
// configure NFC-EE routing
if (mScreenState >= SCREEN_STATE_ON_LOCKED &&
mEeRoutingState == ROUTE_ON_WHEN_SCREEN_ON) {
if (force || !mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE ON");
mNfceeRouteEnabled = true;
mDeviceHost.doSelectSecureElement();
}
} else {
if (force || mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE OFF");
mNfceeRouteEnabled = false;
mDeviceHost.doDeselectSecureElement();
}
}
The service itself is started and stopped in other parts of this class.
See related http://forum.xda-developers.com/showthread.php?t=1712024&page=14

Categories

Resources