Skip to content

Instantly share code, notes, and snippets.

@MotiurRahman
Created February 8, 2019 13:50
Show Gist options
  • Save MotiurRahman/6dd5b734588052d72bb5e27eb2e19764 to your computer and use it in GitHub Desktop.
Save MotiurRahman/6dd5b734588052d72bb5e27eb2e19764 to your computer and use it in GitHub Desktop.
Foreground Service
function monitorLocation() {
function start() {
Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;
Ti.Geolocation.addEventListener("location", function(e) {
Ti.Media.vibrate();
Ti.API.info("@@@ Location Received: " + JSON.stringify(e.coords));
});
}
var hasPermission = Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE);
if (!hasPermission) {
Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE, function(e) {
if (e.success) {
start();
}
});
} else {
start();
}
}
// Start the service.
var intent = Ti.Android.createServiceIntent({
url: "pushService.js",
});
Ti.Android.startService(intent);
// Display the main window.
var window = Ti.UI.createWindow();
window.addEventListener("open", function(e) {
monitorLocation();
});
var button = Titanium.UI.createButton({
title: 'Clear Notification',
top: 20,
color: "red",
width: Ti.UI.SIZE,
height: 50
});
button.addEventListener('click', function(e) {
Ti.Android.stopService(intent);
});
window.add(button);
window.addEventListener("close", function(e) {
// Stop the service on app exit.
Ti.Android.stopService(intent);
});
window.open();
Ti.API.info("@@@ Service started.");
// Gets an intent used to resume the app if running in the background.
function getAppResumeIntent() {
var intent = Ti.App.Android.launchIntent;
if (!intent) {
intent = Ti.Android.createIntent({});
}
return intent;
}
// Put this service into the foreground state.
var notificationId = parseInt(10000 * Math.random());
Ti.Android.currentService.foregroundNotify(notificationId, Ti.Android.createNotification({
contentTitle: "Foreground Service",
contentText: "Content Text",
contentIntent: Ti.Android.createPendingIntent({
// Using the launch intent will resume the app when tapped.
intent: getAppResumeIntent(),
}),
}));
<android xmlns:android="http://schemas.android.com/apk/res/android">
<manifest>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
</manifest>
<services>
<service type="interval" url="pushService.js" />
</services>
</android>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment