Skip to content

Commit

Permalink
Respaldo SV-TL v2.3
Browse files Browse the repository at this point in the history
  • Loading branch information
guillermolc committed Dec 21, 2020
1 parent 5b64a88 commit c4881e7
Show file tree
Hide file tree
Showing 16 changed files with 525 additions and 76 deletions.
6 changes: 5 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,15 @@ dependencies {
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'


// map box
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:9.5.0'
implementation 'com.jakewharton.timber:timber:4.7.1'
implementation 'com.airbnb.android:lottie:3.4.2'


implementation "android.arch.work:work-runtime-ktx:2.3.4"

implementation project(':svtl')
/*implementation 'com.github.guillermo-lagos:SV-TL:1.0.0'*/

testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
Expand Down
18 changes: 18 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
Expand All @@ -20,6 +24,20 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service
android:name=".servicio.EndlessService"
android:enabled="true"
android:exported="false">
</service>


<receiver android:enabled="true" android:name=".servicio.StartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>

</application>

</manifest>
71 changes: 45 additions & 26 deletions app/src/main/java/guillermo/lagos/svtl/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package guillermo.lagos.svtl

import android.os.Bundle
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.RasterLayer
import com.mapbox.mapboxsdk.style.sources.RasterSource
import com.mapbox.mapboxsdk.style.sources.TileSet
import guillermo.lagos.svtl.servicio.Actions
import kotlinx.android.synthetic.main.activity_main.*
import timber.log.Timber
import java.io.File
Expand All @@ -17,43 +21,58 @@ class MainActivity : AppCompatActivity(), OnMapReadyCallback {

var m: MapboxMap? = null


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree())
Mapbox.getInstance(this, getString(R.string.mapbox_access_token))
setContentView(R.layout.activity_main)
map.getMapAsync(this)
}


actionOnService(Actions.START)
init_work()


WorkManager.getInstance().getWorkInfosByTagLiveData("WCH")
.observe(this, { workInfo ->
if (workInfo != null && workInfo[0].state == WorkInfo.State.SUCCEEDED) {
map.getMapAsync(this)
}
})
}


override fun onMapReady(mapboxMap: MapboxMap) {
m = mapboxMap
mapboxMap.setStyle(Style.SATELLITE) { style -> // Connect to localhost even when device is not connected to internet
Mapbox.setConnected(true)
addMbtiles(style)
mapboxMap.apply {
setStyle(offTL(this@MainActivity)) { style ->
Mapbox.setConnected(true)
}
}

}


fun addMbtiles(style: Style) {
val mbtilesFile = File( "asset://santiago.mbtiles")
val sourceId = "your-mb-id"
val mbSource: TLSource
try {
mbSource = TLSource(this, mbtilesFile.absolutePath,"santiago.mbtiles", sourceId)
mbSource.server_on()
style.addSource(RasterSource(mbSource.id, TileSet(null,
mbSource.url), 256)) // 256 * 256 for raster tiles
val rasterLayer = RasterLayer("raster_layer_id", mbSource.id)
style.addLayer(rasterLayer)
// if mbSource contains vector tiles
m?.setStyle(Style.Builder().fromUri("asset://mbStyle.json"))
} catch (e: TLError.CantReadFile) {
Timber.e("CouldNotReadFileError")
}
fun MapboxMap.offTL(context: Context, f_name: String = "chile.zip", db_name: String = "chile.mbtiles"): Style.Builder {
val mbtilesFile = File("asset://$f_name")
val sourceId = "chile"
val mbSource = TLSource(
context,
mbtilesFile.absolutePath,
db_name,
sourceId
)
mbSource?.server_on()
style?.addSource(
RasterSource(
mbSource.id, TileSet(
null,
mbSource.url
), 256
)
)
val rasterLayer = RasterLayer("raster_layer_id", mbSource.id)
style?.addLayer(rasterLayer)
return Style.Builder().fromUri(uri_style)
}

}
36 changes: 36 additions & 0 deletions app/src/main/java/guillermo/lagos/svtl/Utils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package guillermo.lagos.svtl

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.database.sqlite.SQLiteCantOpenDatabaseException
import android.database.sqlite.SQLiteDatabase
import android.os.Build
import android.view.Window
import guillermo.lagos.svtl.servicio.*
import timber.log.Timber
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

fun Activity.actionOnService(action: Actions) {
if (getServiceState(this) == ServiceState.STOPPED && action == Actions.STOP) return
Intent(this, EndlessService::class.java).also {
it.action = action.name
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Timber.e("Starting the service in >=26 Mode")
startForegroundService(it)
return
}
Timber.e("Starting the service in < 26 Mode")
startService(it)
}
}



6 changes: 6 additions & 0 deletions app/src/main/java/guillermo/lagos/svtl/servicio/Actions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package guillermo.lagos.svtl.servicio

enum class Actions {
START,
STOP
}
164 changes: 164 additions & 0 deletions app/src/main/java/guillermo/lagos/svtl/servicio/EndlessService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package guillermo.lagos.svtl.servicio

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.os.SystemClock
import android.util.Log
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.workDataOf
import guillermo.lagos.svtl.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import timber.log.Timber


class EndlessService : Service() {

private var wakeLock: PowerManager.WakeLock? = null
private var isServiceStarted = false

override fun onBind(intent: Intent): IBinder? {
Timber.e("Some component want to bind with the service")
// We don't provide binding, so return null
return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Timber.e("onStartCommand executed with startId: $startId")
if (intent != null) {
val action = intent.action
Timber.e("using an intent with action $action")
when (action) {
Actions.START.name -> startService()
Actions.STOP.name -> stopService()
else -> Timber.e("This should never happen. No action in the received intent")
}
} else {
Timber.e(
"with a null intent. It has been probably restarted by the system."
)
}
// by returning this we make sure the service is restarted if the system kills the service
return START_STICKY
}

override fun onCreate() {
super.onCreate()
Timber.e("The service has been created".toUpperCase())
val notification = createNotification()
startForeground(1, notification)
}

override fun onDestroy() {
super.onDestroy()
Timber.e("The service has been destroyed".toUpperCase())
}

override fun onTaskRemoved(rootIntent: Intent) {
val restartServiceIntent = Intent(applicationContext, EndlessService::class.java).also {
it.setPackage(packageName)
};
val restartServicePendingIntent: PendingIntent = PendingIntent.getService(this, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
applicationContext.getSystemService(Context.ALARM_SERVICE);
val alarmService: AlarmManager = applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager;
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent);
}

private fun startService() {
if (isServiceStarted) return
Timber.e("Starting the foreground service task")
isServiceStarted = true
setServiceState(this, ServiceState.STARTED)

// we need this lock so our service gets not affected by Doze Mode
wakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "EndlessService::lock").apply {
acquire()
}
}

// we're starting a loop in a coroutine
GlobalScope.launch(Dispatchers.IO) {
while (isServiceStarted) {
launch(Dispatchers.IO) {


}
delay(1 * 60 * 1000)
}
Timber.e("End of the loop for the service")
}
}

private fun stopService() {
Timber.e("Stopping the foreground service")
try {
wakeLock?.let {
if (it.isHeld) {
it.release()
}
}
stopForeground(true)
stopSelf()
} catch (e: Exception) {
Timber.e("Service stopped without being started: ${e.message}")
}
isServiceStarted = false
setServiceState(this, ServiceState.STOPPED)
}



private fun createNotification(): Notification {
val notificationChannelId = "ENDLESS SERVICE CHANNEL"

// depending on the Android API that we're dealing with we will have
// to use a specific method to create the notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
notificationChannelId,
"Endless Service notifications channel",
NotificationManager.IMPORTANCE_HIGH
).let {
it.description = "Endless Service channel"
it.enableLights(true)
it.lightColor = Color.RED
it.enableVibration(true)
it.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
it
}
notificationManager.createNotificationChannel(channel)
}

val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}

val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(
this,
notificationChannelId
) else Notification.Builder(this)

return builder
.setContentTitle("Servidor en linea")
/* .setContentText("This is your favorite endless service working")*/
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
/*.setTicker("Ticker text")*/
.setPriority(Notification.PRIORITY_HIGH) // for under android 26 compatibility
.build()
}




}
32 changes: 32 additions & 0 deletions app/src/main/java/guillermo/lagos/svtl/servicio/ServiceState.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package guillermo.lagos.svtl.servicio

import android.content.Context
import android.content.SharedPreferences
import guillermo.lagos.svtl.getPreferences

enum class ServiceState {
STARTED,
STOPPED,
}

private const val name = "SPYSERVICE_KEY"
private const val key = "SPYSERVICE_STATE"

fun setServiceState(context: Context, state: ServiceState) {
val sharedPrefs = getPreferences(context)
sharedPrefs.edit().let {
it.putString(key, state.name)
it.apply()
}
}

fun getServiceState(context: Context): ServiceState {
val sharedPrefs = getPreferences(context)
val value = sharedPrefs.getString(key, ServiceState.STOPPED.name)
return ServiceState.valueOf(value!!)
}

fun getPreferences(context: Context): SharedPreferences {
return context.getSharedPreferences(name, 0)
}

Loading

0 comments on commit c4881e7

Please sign in to comment.