Skip to content

Commit

Permalink
Merge pull request #116 from RADAR-base/feature-auto-update-notificat…
Browse files Browse the repository at this point in the history
…ions

Feature auto update notifications
  • Loading branch information
peyman-mohtashami authored Jun 19, 2021
2 parents 182d653 + be94d6c commit dbfb2e0
Show file tree
Hide file tree
Showing 19 changed files with 1,049 additions and 5 deletions.
23 changes: 21 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ android {
applicationId 'org.radarcns.detail'
minSdkVersion 21
targetSdkVersion 30
versionCode 51
versionName '1.0.12'
versionCode 52
versionName '1.0.13'
manifestPlaceholders = ['appAuthRedirectScheme': 'org.radarbase.passive.app']
multiDexEnabled true
}
Expand Down Expand Up @@ -104,6 +104,25 @@ dependencies {

testImplementation 'junit:junit:4.13.2'
testRuntimeOnly 'org.slf4j:slf4j-simple:1.7.30'

implementation("com.android.volley:volley:1.2.0")

// Kotlin + coroutines
implementation("androidx.work:work-runtime-ktx:2.5.0")

// optional - RxJava2 support
implementation("androidx.work:work-rxjava2:2.5.0")

// optional - GCMNetworkManager support
implementation("androidx.work:work-gcm:2.5.0")

// optional - Test helpers
androidTestImplementation("androidx.work:work-testing:2.5.0")

// optional - Multiprocess support
implementation "androidx.work:work-multiprocess:2.5.0"

implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1"
}

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
Expand Down
17 changes: 16 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

<supports-screens android:largeScreens="true"
android:xlargeScreens="true" />

Expand All @@ -29,6 +31,17 @@
android:name=".RadarApplicationImpl"
android:fullBackupContent="@xml/backup_descriptor"
android:installLocation="internalOnly">

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>

<receiver
android:enabled="false"
android:name=".MainActivityBootStarter">
Expand Down Expand Up @@ -88,9 +101,11 @@
android:parentActivityName=".MainActivityImpl"/>
<activity android:name=".SettingsActivity"
android:parentActivityName=".MainActivityImpl"/>

<activity android:name=".UpdatesActivity"
android:parentActivityName=".MainActivityImpl"/>
<service android:name=".RadarServiceImpl"/>
<service android:name=".AuthServiceImpl"/>
<service android:name=".UpdateScheduledService" />

<!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
Expand Down
10 changes: 10 additions & 0 deletions app/src/main/res/drawable/ic_baseline_update_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M21,10.12h-6.78l2.74,-2.82c-2.73,-2.7 -7.15,-2.8 -9.88,-0.1c-2.73,2.71 -2.73,7.08 0,9.79s7.15,2.71 9.88,0C18.32,15.65 19,14.08 19,12.1h2c0,1.98 -0.88,4.55 -2.64,6.29c-3.51,3.48 -9.21,3.48 -12.72,0c-3.5,-3.47 -3.53,-9.11 -0.02,-12.58s9.14,-3.47 12.65,0L21,3V10.12zM12.5,8v4.25l3.5,2.08l-0.72,1.21L11,13V8H12.5z"/>
</vector>
2 changes: 1 addition & 1 deletion app/src/main/res/layout/activity_settings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
android:onClick="startReset"
app:layout_constraintTop_toBottomOf="@id/enableDataHighPrioritySwitch"
app:layout_constraintBottom_toBottomOf="@id/constraintLayout"
app:layout_constraintStart_toStartOf="@id/constraintLayout" />
app:layout_constraintStart_toStartOf="@id/constraintLayout"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

Expand Down
12 changes: 12 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,16 @@
<string name="appbar_scrolling_view_behavior" translatable="false">com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior</string>
<string name="bootstart_title">Please start RADAR pRMT</string>
<string name="bootstart_text">RADAR pRMT has automatically been stopped. Please press this notification to start it again.</string>

<!-- Updates -->
<string name="updates">Updates</string>
<string name="update_notification_content">New version is available.\nClick to download.</string>
<string name="currentVersion">Version: %1$s</string>
<string name="new_version_available">A new version of %1$s App (%2$s) is available.</string>
<string name="new_version_not_available">You installed the latest version of %1$s App.</string>
<string name="no">No</string>
<string name="dont_show_again">Don\'t Show Again</string>
<string name="start_downloading">Start Downloading</string>
<string name="update_question">Do you want to install it?</string>
<string name="error_in_package_name">Error in package name!</string>
</resources>
21 changes: 21 additions & 0 deletions app/src/main/res/xml/provider_paths.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
<!-- <files-path name="external_files" path="."/>-->
</paths>
16 changes: 16 additions & 0 deletions app/src/main/res/xml/remote_config_defaults.xml
Original file line number Diff line number Diff line change
Expand Up @@ -86,5 +86,21 @@
<key>privacy_policy</key>
<value>http://info.thehyve.nl/radar-cns-privacy-policy</value>
</entry>
<entry>
<key>update_check</key>
<value>true</value>
</entry>
<entry>
<key>update_check_notification</key>
<value>true</value>
</entry>
<entry>
<key>update_check_frequency</key>
<value>day</value>
</entry>
<entry>
<key>update_releases_url</key>
<value>https://api.github.com/repos/RADAR-base/radar-prmt-android/releases</value>
</entry>
</defaultsMap>
<!-- END xml_defaults -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.radarcns.detail

import android.content.Context
import android.content.pm.PackageManager.NameNotFoundException
import android.util.Log

fun isPackageNameSame(context: Context, apkPath: String): Boolean {
return context.packageName == getUpdatePackageName(context, apkPath)
}

fun getUpdatePackageName(context: Context, apkPath: String): String? {
try {
return context.packageManager.getPackageArchiveInfo(apkPath, 0)?.packageName
} catch (e: NameNotFoundException) {
Log.e("ComparePackageNames", "Cannot resolve package name for $apkPath", e)
e.printStackTrace()
}
return null
}
50 changes: 50 additions & 0 deletions app/src/selfRelease/java/org/radarcns/detail/CompareVersions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package org.radarcns.detail

import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import org.json.JSONObject
import org.radarcns.detail.UpdateScheduledService.Companion.UPDATE_VERSION_NAME_KEY
import org.radarcns.detail.UpdateScheduledService.Companion.UPDATE_VERSION_URL_KEY

fun getUpdatePackage(context: Context, response: String): JSONObject? {
val updatePackage = getUpdatePackageVersionAndUrl(response)
val currentPackageVersion = getInstalledPackageVersion(context)

val pattern = Regex("\\d+(\\.\\d+)+")

val rawCurrentPackageVersion = currentPackageVersion?.let { pattern.find(it)?.value }
val rawUpdatePackageVersion = updatePackage?.getString(UPDATE_VERSION_NAME_KEY)?.let { pattern.find(it)?.value }

if (rawCurrentPackageVersion != rawUpdatePackageVersion) {
return updatePackage
}
return null
}

fun getInstalledPackageVersion(context: Context): String? {
try {
return context.packageManager.getPackageInfo(context.packageName, 0).versionName
} catch (e: PackageManager.NameNotFoundException) {
Log.e("CompareVersions", "Cannot resolve version for " + context.packageName, e)
e.printStackTrace()
}
return null
}

fun getUpdatePackageVersionAndUrl(response: String): JSONObject? {
val responseObject = Json.parseToJsonElement(response)
if (responseObject.jsonArray.size > 0) {
val latestRelease = responseObject.jsonArray[0]
val tagName = latestRelease.jsonObject["tag_name"]?.toString()?.replace("\"", "")
val browserDownloadUrl = latestRelease.jsonObject["assets"]?.jsonArray?.get(0)?.jsonObject?.getValue("browser_download_url").toString().replace("\"", "")
val updateApk = JSONObject()
updateApk.put(UPDATE_VERSION_URL_KEY, browserDownloadUrl)
updateApk.put(UPDATE_VERSION_NAME_KEY, tagName)
return updateApk
}
return null
}
100 changes: 100 additions & 0 deletions app/src/selfRelease/java/org/radarcns/detail/DownloadFileFromUrl.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package org.radarcns.detail

import android.content.Context
import android.os.AsyncTask
import android.widget.ProgressBar
import java.io.*
import java.net.HttpURLConnection
import java.net.URL

class DownloadFileFromUrl(context: Context, delegate: TaskDelegate) :
AsyncTask<String?, Int?, String?>() {

private val mDelegate: TaskDelegate = delegate

private val mContext: Context = context

var bar: ProgressBar? = null

override fun doInBackground(vararg params: String?): String? {
var input: InputStream? = null
var output: OutputStream? = null
var connection: HttpURLConnection? = null
try {
val url = URL(params[0])
connection = url.openConnection() as HttpURLConnection
connection.connect()

// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.responseCode !== HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.responseCode
.toString() + " " + connection.responseMessage
}

// this will be useful to display download percentage
// might be -1: server did not report the length
val fileLength: Int = connection.contentLength

// download the file
input = connection.inputStream

val outputFile = File(mContext.filesDir, DOWNLOADED_FILE)
if (outputFile.exists()) {
outputFile.delete()
}

outputFile.setReadable(true, false)
output = FileOutputStream(outputFile)

val data = ByteArray(1024) //4096
var total: Long = 0
var count: Int
while (input.read(data).also { count = it } != -1) {
// allow canceling with back button
if (isCancelled) {
input.close()
return null
}
total += count.toLong()
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((total * 100 / fileLength).toInt())
output.write(data, 0, count)
}
} catch (e: Exception) {
return e.toString()
} finally {
try {
output?.close()
input?.close()
} catch (ignored: IOException) {
}
connection?.disconnect()
}
return null
}

override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
bar?.progress = values[0]!!
}

override fun onPostExecute(s: String?) {
super.onPostExecute(s)
mDelegate.taskCompletionResult("Post Exec")
}

fun setProgressBar(bar: ProgressBar?) {
this.bar = bar
}

companion object {
const val DOWNLOADED_FILE = "app-release.apk"
}
}

interface TaskDelegate {
fun taskCompletionResult(result: String?)
}

51 changes: 51 additions & 0 deletions app/src/selfRelease/java/org/radarcns/detail/MainActivityImpl.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2017 The Hyve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.radarcns.detail

import android.content.Intent
import android.os.Bundle
import android.view.View
import org.radarbase.android.MainActivity
import org.radarbase.android.MainActivityView
import org.radarbase.android.RadarApplication.Companion.radarApp

class MainActivityImpl : MainActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
radarApp.notificationHandler.cancel(MainActivityBootStarter.BOOT_START_NOTIFICATION_ID)
super.onCreate(savedInstanceState)
}

override fun createView(): MainActivityView {
return MainActivityViewImpl(this)
}

fun logout(@Suppress("UNUSED_PARAMETER")view: View) {
logout(true)
}

fun showInfo(@Suppress("UNUSED_PARAMETER")view: View) {
startActivity(Intent(this, InfoActivity::class.java))
}

fun showSettings(@Suppress("UNUSED_PARAMETER")view: View) {
startActivity(Intent(this, SettingsActivity::class.java))
}

fun showUpdates(@Suppress("UNUSED_PARAMETER")view: View) {
startActivity(Intent(this, UpdatesActivity::class.java))
}
}
Loading

0 comments on commit dbfb2e0

Please sign in to comment.