Skip to content

Commit 51eef77

Browse files
committed
Refactor MainService to prevent unnecessary activity starts
There should be no logic change. Just moving the code in separate methods and directly check the condition instead of checking in the activity. Most of the time this will safe jumping between activities and service as permissions are only requested the first time. This helps when automating the start process of a session.
1 parent ac3de41 commit 51eef77

File tree

3 files changed

+101
-96
lines changed

3 files changed

+101
-96
lines changed

app/src/main/java/net/christianbeier/droidvnc_ng/MainService.java

Lines changed: 99 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
package net.christianbeier.droidvnc_ng;
2323

24+
import android.Manifest;
2425
import android.annotation.SuppressLint;
2526
import android.app.Notification;
2627
import android.app.NotificationChannel;
@@ -31,6 +32,7 @@
3132
import android.content.Context;
3233
import android.content.Intent;
3334
import android.content.SharedPreferences;
35+
import android.content.pm.PackageManager;
3436
import android.content.pm.ServiceInfo;
3537
import android.net.ConnectivityManager;
3638
import android.net.Network;
@@ -353,36 +355,7 @@ public int onStartCommand(Intent intent, int flags, int startId)
353355
stopScreenCapture();
354356
startScreenCapture();
355357
} else {
356-
DisplayMetrics displayMetrics = Utils.getDisplayMetrics(this, Display.DEFAULT_DISPLAY);
357-
Intent startIntent = Objects.requireNonNull(MainServicePersistData.loadStartIntent(this));
358-
int port = startIntent.getIntExtra(EXTRA_PORT, PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.PREFS_KEY_SETTINGS_PORT, mDefaults.getPort()));
359-
String password = startIntent.getStringExtra(EXTRA_PASSWORD) != null ? startIntent.getStringExtra(EXTRA_PASSWORD) : PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PREFS_KEY_SETTINGS_PASSWORD, mDefaults.getPassword());
360-
// get device name
361-
String name = Utils.getDeviceName(this);
362-
363-
boolean status = vncStartServer(displayMetrics.widthPixels,
364-
displayMetrics.heightPixels,
365-
port,
366-
name,
367-
password,
368-
getFilesDir().getAbsolutePath() + File.separator + "novnc");
369-
Intent answer = new Intent(ACTION_START);
370-
answer.putExtra(EXTRA_REQUEST_ID, startIntent.getStringExtra(EXTRA_REQUEST_ID));
371-
answer.putExtra(EXTRA_REQUEST_SUCCESS, status);
372-
sendBroadcastToOthersAndUs(answer);
373-
374-
if (status) {
375-
MainServicePersistData.saveLastActiveState(this, true);
376-
startScreenCapture();
377-
registerNSD(name, port);
378-
updateNotification();
379-
// if we got here, we want to restart if we were killed
380-
return START_REDELIVER_INTENT;
381-
} else {
382-
MainServicePersistData.clear(this);
383-
stopSelfByUs();
384-
return START_NOT_STICKY;
385-
}
358+
return step4StartCapture();
386359
}
387360
}
388361

@@ -399,69 +372,14 @@ public int onStartCommand(Intent intent, int flags, int startId)
399372
// or ask for capturing permission first (then going in step 4)
400373
}
401374

402-
Intent startIntent = Objects.requireNonNull(MainServicePersistData.loadStartIntent(this));
403-
404-
if (mResultCode != 0 && mResultData != null
405-
|| (Build.VERSION.SDK_INT >= 30 && startIntent.getBooleanExtra(EXTRA_FALLBACK_SCREEN_CAPTURE, false))) {
406-
DisplayMetrics displayMetrics = Utils.getDisplayMetrics(this, Display.DEFAULT_DISPLAY);
407-
int port = startIntent.getIntExtra(EXTRA_PORT, PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.PREFS_KEY_SETTINGS_PORT, mDefaults.getPort()));
408-
String password = startIntent.getStringExtra(EXTRA_PASSWORD) != null ? startIntent.getStringExtra(EXTRA_PASSWORD) : PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PREFS_KEY_SETTINGS_PASSWORD, mDefaults.getPassword());
409-
String name = Utils.getDeviceName(this);
410-
boolean status = vncStartServer(displayMetrics.widthPixels,
411-
displayMetrics.heightPixels,
412-
port,
413-
name,
414-
password,
415-
getFilesDir().getAbsolutePath() + File.separator + "novnc");
416-
417-
Intent answer = new Intent(ACTION_START);
418-
answer.putExtra(EXTRA_REQUEST_ID, startIntent.getStringExtra(EXTRA_REQUEST_ID));
419-
answer.putExtra(EXTRA_REQUEST_SUCCESS, status);
420-
sendBroadcastToOthersAndUs(answer);
421-
422-
if(status) {
423-
MainServicePersistData.saveLastActiveState(this, true);
424-
startScreenCapture();
425-
registerNSD(name, port);
426-
updateNotification();
427-
// if we got here, we want to restart if we were killed
428-
return START_REDELIVER_INTENT;
429-
} else {
430-
MainServicePersistData.clear(this);
431-
stopSelfByUs();
432-
return START_NOT_STICKY;
433-
}
434-
} else {
435-
Log.i(TAG, "Requesting confirmation");
436-
// This initiates a prompt dialog for the user to confirm screen projection.
437-
Intent mediaProjectionRequestIntent = new Intent(this, MediaProjectionRequestActivity.class);
438-
mediaProjectionRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
439-
startActivity(mediaProjectionRequestIntent);
440-
// if screen capturing was not started, we don't want a restart if we were killed
441-
// especially, we don't want the permission asking to replay.
442-
return START_NOT_STICKY;
443-
}
375+
return step3RequestProjectionPermission();
444376
}
445377

446378
if(ACTION_HANDLE_INPUT_RESULT.equals(intent.getAction()) && MainServicePersistData.loadStartIntent(this) != null) {
447379
Log.d(TAG, "onStartCommand: handle input result");
448380
// Step 2: coming back from input permission check, now setup InputService and ask for write storage permission or notification permission
449381
InputService.isInputEnabled = intent.getBooleanExtra(EXTRA_INPUT_RESULT, false);
450-
if(Build.VERSION.SDK_INT < 33) {
451-
Intent writeStorageRequestIntent = new Intent(this, WriteStorageRequestActivity.class);
452-
writeStorageRequestIntent.putExtra(
453-
EXTRA_FILE_TRANSFER,
454-
Objects.requireNonNull(MainServicePersistData.loadStartIntent(this)).getBooleanExtra(EXTRA_FILE_TRANSFER, PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREFS_KEY_SETTINGS_FILE_TRANSFER, mDefaults.getFileTransfer())));
455-
writeStorageRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
456-
startActivity(writeStorageRequestIntent);
457-
} else {
458-
Intent notificationRequestIntent = new Intent(this, NotificationRequestActivity.class);
459-
notificationRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
460-
startActivity(notificationRequestIntent);
461-
}
462-
// if screen capturing was not started, we don't want a restart if we were killed
463-
// especially, we don't want the permission asking to replay.
464-
return START_NOT_STICKY;
382+
return step2RequestStorageOrNotifications();
465383
}
466384

467385
if(ACTION_START.equals(intent.getAction())) {
@@ -487,13 +405,7 @@ public int onStartCommand(Intent intent, int flags, int startId)
487405
InputService.scaling = PreferenceManager.getDefaultSharedPreferences(this).getFloat(Constants.PREFS_KEY_SERVER_LAST_SCALING, new Defaults(this).getScaling());
488406

489407
// Step 1: check input/start-on-boot permission
490-
Intent inputRequestIntent = new Intent(this, InputRequestActivity.class);
491-
inputRequestIntent.putExtra(EXTRA_VIEW_ONLY, intent.getBooleanExtra(EXTRA_VIEW_ONLY, mDefaults.getViewOnly()));
492-
inputRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
493-
startActivity(inputRequestIntent);
494-
// if screen capturing was not started, we don't want a restart if we were killed
495-
// especially, we don't want the permission asking to replay.
496-
return START_NOT_STICKY;
408+
return step1ConnectInputService(intent.getBooleanExtra(EXTRA_VIEW_ONLY, mDefaults.getViewOnly()));
497409
}
498410

499411
if(ACTION_STOP.equals(intent.getAction())) {
@@ -567,6 +479,99 @@ public int onStartCommand(Intent intent, int flags, int startId)
567479
return START_NOT_STICKY;
568480
}
569481

482+
private int step1ConnectInputService(boolean viewOnly) {
483+
if (!InputService.isConnected()) {
484+
Intent inputRequestIntent = new Intent(this, InputRequestActivity.class);
485+
inputRequestIntent.putExtra(EXTRA_VIEW_ONLY, viewOnly);
486+
inputRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
487+
startActivity(inputRequestIntent);
488+
// if screen capturing was not started, we don't want a restart if we were killed
489+
// especially, we don't want the permission asking to replay.
490+
return START_NOT_STICKY;
491+
} else {
492+
InputService.isInputEnabled = true;
493+
return step2RequestStorageOrNotifications();
494+
}
495+
}
496+
497+
private int step2RequestStorageOrNotifications() {
498+
if (Build.VERSION.SDK_INT < 33) {
499+
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
500+
!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(WriteStorageRequestActivity.PREFS_KEY_PERMISSION_ASKED_BEFORE, false)) {
501+
Intent writeStorageRequestIntent = new Intent(this, WriteStorageRequestActivity.class);
502+
writeStorageRequestIntent.putExtra(
503+
EXTRA_FILE_TRANSFER,
504+
Objects.requireNonNull(MainServicePersistData.loadStartIntent(this)).getBooleanExtra(EXTRA_FILE_TRANSFER, PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.PREFS_KEY_SETTINGS_FILE_TRANSFER, mDefaults.getFileTransfer())));
505+
writeStorageRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
506+
startActivity(writeStorageRequestIntent);
507+
} else {
508+
return step3RequestProjectionPermission();
509+
}
510+
} else {
511+
if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED &&
512+
!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(NotificationRequestActivity.PREFS_KEY_POST_NOTIFICATION_PERMISSION_ASKED_BEFORE, false)) {
513+
Intent notificationRequestIntent = new Intent(this, NotificationRequestActivity.class);
514+
notificationRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
515+
startActivity(notificationRequestIntent);
516+
} else {
517+
return step3RequestProjectionPermission();
518+
}
519+
}
520+
// if screen capturing was not started, we don't want a restart if we were killed
521+
// especially, we don't want the permission asking to replay.
522+
return START_NOT_STICKY;
523+
}
524+
525+
private int step3RequestProjectionPermission() {
526+
Intent startIntent = Objects.requireNonNull(MainServicePersistData.loadStartIntent(this));
527+
528+
if (mResultCode != 0 && mResultData != null
529+
|| (Build.VERSION.SDK_INT >= 30 && startIntent.getBooleanExtra(EXTRA_FALLBACK_SCREEN_CAPTURE, false))) {
530+
return step4StartCapture();
531+
} else {
532+
Log.i(TAG, "Requesting confirmation");
533+
// This initiates a prompt dialog for the user to confirm screen projection.
534+
Intent mediaProjectionRequestIntent = new Intent(this, MediaProjectionRequestActivity.class);
535+
mediaProjectionRequestIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
536+
startActivity(mediaProjectionRequestIntent);
537+
// if screen capturing was not started, we don't want a restart if we were killed
538+
// especially, we don't want the permission asking to replay.
539+
return START_NOT_STICKY;
540+
}
541+
}
542+
543+
private int step4StartCapture() {
544+
DisplayMetrics displayMetrics = Utils.getDisplayMetrics(this, Display.DEFAULT_DISPLAY);
545+
Intent startIntent = Objects.requireNonNull(MainServicePersistData.loadStartIntent(this));
546+
int port = startIntent.getIntExtra(EXTRA_PORT, PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.PREFS_KEY_SETTINGS_PORT, mDefaults.getPort()));
547+
String password = startIntent.getStringExtra(EXTRA_PASSWORD) != null ? startIntent.getStringExtra(EXTRA_PASSWORD) : PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PREFS_KEY_SETTINGS_PASSWORD, mDefaults.getPassword());
548+
String name = Utils.getDeviceName(this);
549+
boolean status = vncStartServer(displayMetrics.widthPixels,
550+
displayMetrics.heightPixels,
551+
port,
552+
name,
553+
password,
554+
getFilesDir().getAbsolutePath() + File.separator + "novnc");
555+
556+
Intent answer = new Intent(ACTION_START);
557+
answer.putExtra(EXTRA_REQUEST_ID, startIntent.getStringExtra(EXTRA_REQUEST_ID));
558+
answer.putExtra(EXTRA_REQUEST_SUCCESS, status);
559+
sendBroadcastToOthersAndUs(answer);
560+
561+
if (status) {
562+
MainServicePersistData.saveLastActiveState(this, true);
563+
startScreenCapture();
564+
registerNSD(name, port);
565+
updateNotification();
566+
// if we got here, we want to restart if we were killed
567+
return START_REDELIVER_INTENT;
568+
} else {
569+
MainServicePersistData.clear(this);
570+
stopSelfByUs();
571+
return START_NOT_STICKY;
572+
}
573+
}
574+
570575
@SuppressLint("WakelockTimeout")
571576
@SuppressWarnings("unused")
572577
static void onClientConnected(long client) {

app/src/main/java/net/christianbeier/droidvnc_ng/NotificationRequestActivity.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class NotificationRequestActivity extends AppCompatActivity {
1818

1919
private static final String TAG = "NotificationRequestActivity";
2020
private static final int REQUEST_POST_NOTIFICATION = 45;
21-
private static final String PREFS_KEY_POST_NOTIFICATION_PERMISSION_ASKED_BEFORE = "post_notification_permission_asked_before";
21+
public static final String PREFS_KEY_POST_NOTIFICATION_PERMISSION_ASKED_BEFORE = "post_notification_permission_asked_before";
2222

2323

2424
@Override

app/src/main/java/net/christianbeier/droidvnc_ng/WriteStorageRequestActivity.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class WriteStorageRequestActivity extends AppCompatActivity {
3838

3939
private static final String TAG = "WriteStorageRequestActivity";
4040
private static final int REQUEST_WRITE_STORAGE = 44;
41-
private static final String PREFS_KEY_PERMISSION_ASKED_BEFORE = "write_storage_permission_asked_before";
41+
public static final String PREFS_KEY_PERMISSION_ASKED_BEFORE = "write_storage_permission_asked_before";
4242

4343
@Override
4444
protected void onCreate(Bundle savedInstanceState) {

0 commit comments

Comments
 (0)