Skip to content
This repository has been archived by the owner on Jan 18, 2022. It is now read-only.

Commit

Permalink
v0.4.0-alpha; change from long running foreground service to intent s…
Browse files Browse the repository at this point in the history
…ervice to save cpu load and time; add looper mechanism to prevent early stopping; add trim memory mechanism to keep alive;

Signed-off-by: Jerry Chen <jerryc05@qq.com>
  • Loading branch information
Jerry Chen committed Aug 2, 2019
1 parent 4c12c86 commit 12b233c
Show file tree
Hide file tree
Showing 11 changed files with 267 additions and 242 deletions.
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ android {
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "0.3.2"
versionName "0.4.0-alpha"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
resConfigs "xxhdpi"
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
android:label="@string/app_name"
android:theme="@style/AppTheme"
tools:ignore="AllowBackup">

<activity android:name=".activities.SettingActivity" />

<activity android:name=".activities.MainActivity">
Expand Down
111 changes: 61 additions & 50 deletions app/src/main/java/jerryc05/unlockme/activities/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ public final class MainActivity extends Activity
implements OnClickListener, OnCheckedChangeListener {

final static String
TAG = MainActivity.class.getSimpleName();
TAG = "MainActivity";
public final static int
REQUEST_CODE_DEVICE_ADMIN = 0,
REQUEST_CODE_CAMERA_AND_WRITE_EXTERNAL = 1;

public ReentrantLock requestDeviceAdminLock;
public static ThreadPoolExecutor threadPoolExecutor;
public ReentrantLock requestDeviceAdminLock; // todo
private ThreadPoolExecutor threadPoolExecutor;

@IntDef({REQUEST_CODE_DEVICE_ADMIN, REQUEST_CODE_CAMERA_AND_WRITE_EXTERNAL})
@Retention(RetentionPolicy.SOURCE)
Expand All @@ -65,49 +65,53 @@ protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.activity_main_button_front)
.setOnClickListener(MainActivity.this);
findViewById(R.id.activity_main_button_back)
.setOnClickListener(MainActivity.this);
findViewById(R.id.activity_main_button_stopService)
.setOnClickListener(MainActivity.this);

final Switch forceAPI1 =
findViewById(R.id.activity_main_api1Switch);
forceAPI1.setOnCheckedChangeListener(MainActivity.this);
forceAPI1.setChecked(!CameraBaseAPIClass.getPreferCamera2(
MainActivity.this));
getThreadPoolExecutor().execute(
new Runnable() {
@Override
public void run() {
findViewById(R.id.activity_main_button_front)
.setOnClickListener(MainActivity.this);
findViewById(R.id.activity_main_button_back)
.setOnClickListener(MainActivity.this);
findViewById(R.id.activity_main_button_stopService)
.setOnClickListener(MainActivity.this);

final Switch forceAPI1 = findViewById(R.id.activity_main_api1Switch);
forceAPI1.setOnCheckedChangeListener(MainActivity.this);
runOnUiThread(new Runnable() {
@Override
public void run() {
forceAPI1.setChecked(!CameraBaseAPIClass.getPreferCamera2(
getApplicationContext()));
}
});
}
}
);
}

@Override
protected void onStart() {
super.onStart();

getThreadPoolExecutor().execute(new Runnable() {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
if (requestDeviceAdminLock != null)
requestDeviceAdminLock.lock();
DeviceAdminHelper.requestPermission(MainActivity.this);
DeviceAdminHelper.requestPermission(MainActivity.this); //todo
checkUpdate();
}
});
}

@Override
protected void onStop() {
super.onStop();

if (BuildConfig.DEBUG)
Log.d(TAG, "onStop: ");
}

@Override
protected void onDestroy() {
super.onDestroy();

if (BuildConfig.DEBUG)
Log.d(TAG, "onDestroy: ");

if (threadPoolExecutor != null) {
threadPoolExecutor.shutdownNow();
threadPoolExecutor = null;
Expand All @@ -118,22 +122,25 @@ protected void onDestroy() {
protected void onActivityResult(@RequestCodes int requestCode,
int resultCode,
@Nullable Intent data) {
if (requestCode == REQUEST_CODE_DEVICE_ADMIN &&
resultCode == RESULT_CANCELED)
DeviceAdminHelper.onRequestPermissionFinished(this);
if (requestCode == RESULT_CANCELED &&
resultCode == REQUEST_CODE_DEVICE_ADMIN)
DeviceAdminHelper.onRequestPermissionFinished(this); //todo
}

@Override
public void onRequestPermissionsResult(int requestCode,
public void onRequestPermissionsResult(@RequestCodes int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_CAMERA_AND_WRITE_EXTERNAL)
CameraBaseAPIClass.onRequestPermissionFinished(
this, grantResults);
getApplicationContext(), grantResults);
}

@Override
public void onClick(@NonNull View view) {
if (BuildConfig.DEBUG)
Log.d(TAG, "onClick: ");

threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
Expand All @@ -144,8 +151,7 @@ public void run() {
if (id == R.id.activity_main_button_stopService)
stopService(intent);

else if (CameraBaseAPIClass.requestPermissions(
MainActivity.this)) {
else if (CameraBaseAPIClass.requestPermissions(MainActivity.this)) {
intent.setAction(ACTION_CAPTURE_IMAGE);
intent.putExtra(EXTRA_CAMERA_FACING,
id == R.id.activity_main_button_front);
Expand Down Expand Up @@ -181,7 +187,7 @@ public void rejectedExecution(Runnable runnable,
+ "\non " + TAG + " rejected:\n >>> "
+ runnable.toString(),
"threadPoolExecutor#rejectedExecution()",
MainActivity.this);
getApplicationContext());
}
};
final int processorCount = Runtime.getRuntime().availableProcessors();
Expand All @@ -204,46 +210,51 @@ void checkUpdate() {
.setConnectTimeout(1000)
.setReadTimeout(1000)
.setUseCache(false)
.connect(this);
.connect(getApplicationContext());

final String latest = new JSONArray(connectionBuilder.getResult())
.getJSONObject(0)
.getString("name").substring(1);

if (!latest.equals(BuildConfig.VERSION_NAME))
if (!latest.equals(BuildConfig.VERSION_NAME)) {
if (BuildConfig.DEBUG)
Log.d(TAG, "checkUpdate: " + latest);

final String tagURL = "https://github.com/jerryc05/UnlockMe/releases/tag/v";
final DialogInterface.OnClickListener positive =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(tagURL + latest)));
}
};

runOnUiThread(new Runnable() {
@Override
public void run() {
final String URL = "https://github.com/jerryc05/UnlockMe/releases/tag/v";
new AlertDialog.Builder(MainActivity.this)
.setTitle("New Version Available")
.setMessage("Do you want to upgrade from\n\tv" +
BuildConfig.VERSION_NAME + " to v" + latest + '?')
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(URL + latest)));
}
})
.setPositiveButton("YES", positive)
.setNegativeButton("NO", null)
.setIcon(R.drawable.ic_round_info)
.show();
}
});
}

} catch (final UnknownHostException e) {
UserInterface.showExceptionToNotificationNoRethrow(
"Cannot connect to github.com!\n>>> " + e.toString(),
"checkUpdate()", this);
} catch (final IllegalStateException e) {
UserInterface.notifyToUI("Update Interrupted",
"Will not connect through cellular data!", this);
"checkUpdate()", getApplicationContext());

} catch (final Exception e) {
UserInterface.showExceptionToNotificationNoRethrow(
e.toString(), "checkUpdate()", this);
e.toString(), "checkUpdate()", getApplicationContext());

} finally {
if (connectionBuilder != null)
connectionBuilder.disconnect();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ public void run() {

public static void onRequestPermissionFinished(
@NonNull final MainActivity activity) {
if (!getDevicePolicyManager(activity).isAdminActive(
getComponentName(activity))) {
final Context applicationContext = activity.getApplicationContext();

if (!getDevicePolicyManager(applicationContext)
.isAdminActive(getComponentName(applicationContext))) {
if (activity.requestDeviceAdminLock == null)
activity.requestDeviceAdminLock = new ReentrantLock();
activity.requestDeviceAdminLock.lock();
Expand All @@ -65,7 +67,7 @@ public static void onRequestPermissionFinished(
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog,
final int which) {
int which) {
System.exit(1);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
public final class URLConnectionBuilder {

private final static String
TAG = URLConnectionBuilder.class.getSimpleName();
TAG = "URLConnectionBuilder";

private final static int
TRANSPORT_CELLULAR = 0,
Expand Down Expand Up @@ -100,9 +100,11 @@ public static URLConnectionBuilder post(@NonNull final String baseURL)

public URLConnectionBuilder connect(@NonNull final Context context)
throws IOException {
if (BuildConfig.DEBUG)
Log.d(TAG, "connect: " + urlConnection.getURL());

checkNullUrlConnection("run");
if (!wifiOnly ||
getNetworkType(context) == TRANSPORT_WIFI)
if (!wifiOnly || getNetworkType(context) == TRANSPORT_WIFI)
(isHTTP ? urlConnection
: (HttpsURLConnection) urlConnection).connect();
else
Expand Down Expand Up @@ -131,7 +133,7 @@ public String getResult(@NonNull final String charset) throws IOException {
}

if (BuildConfig.DEBUG)
Log.d(TAG, "connect: Response code = " + (isHTTP
Log.v(TAG, "connect: Response code = " + (isHTTP
? (HttpURLConnection) urlConnection
: (HttpsURLConnection) urlConnection)
.getResponseCode()
Expand All @@ -154,13 +156,13 @@ public String getResult() throws IOException {
}

public void disconnect() {
if (BuildConfig.DEBUG)
Log.d(TAG, "disconnect: " + urlConnection.getURL());

checkNullUrlConnection("disconnect");
(isHTTP ? (HttpURLConnection) urlConnection
: (HttpsURLConnection) urlConnection)
.disconnect();

if (BuildConfig.DEBUG)
Log.d(TAG, "disconnect: " + urlConnection.getURL());
}

private static int getNetworkType(@NonNull final Context context)
Expand All @@ -182,7 +184,7 @@ private static int getNetworkType(@NonNull final Context context)
} else {
final Network network = mConnectivityManager.getActiveNetwork();
if (network == null)
throw new IllegalStateException("Network disconnected!");
throw new IllegalStateException("No active network!");

final NetworkCapabilities networkCapabilities =
mConnectivityManager.getNetworkCapabilities(network);
Expand Down Expand Up @@ -212,12 +214,12 @@ public URLConnectionBuilder setRequestMethod(
return this;
}

public URLConnectionBuilder setConnectTimeout(final int connectTimeout) {
public URLConnectionBuilder setConnectTimeout(int connectTimeout) {
urlConnection.setConnectTimeout(connectTimeout);
return this;
}

public URLConnectionBuilder setReadTimeout(final int readTimeout) {
public URLConnectionBuilder setReadTimeout(int readTimeout) {
urlConnection.setReadTimeout(readTimeout);
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ builder, getNotificationManager(context),
* @param cancelNotificationID pass -1 to stop dismissing notification.
*/
private static PendingIntent getUpdateNotificationPendingIntent(
final int cancelNotificationID,
int cancelNotificationID,
@NonNull final Context context) {

final Intent intent = new Intent(context, ForegroundService.class);
Expand All @@ -144,11 +144,11 @@ private static PendingIntent getUpdateNotificationPendingIntent(
final PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
pendingIntent = PendingIntent.getService(context,
ForegroundService.class.getSimpleName().hashCode(),
"ForegroundService".hashCode(),
intent, PendingIntent.FLAG_UPDATE_CURRENT);
else
pendingIntent = PendingIntent.getForegroundService(context,
ForegroundService.class.getSimpleName().hashCode(),
"ForegroundService".hashCode(),
intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
Expand All @@ -162,7 +162,7 @@ public static void notifyToForegroundService(@NonNull final Service service) {
R.drawable.ic_launcher_smartphone_lock_foreground);

service.startForeground(title.hashCode(),
UserInterface.setNotificationChannel(builder,
UserInterface.setNotificationChannel(builder, // todo use low priority
getNotificationManager(service), title,
"Background service notification for UnlockMe.",
true).build());
Expand Down
Loading

0 comments on commit 12b233c

Please sign in to comment.