android: move to separate folder, hide keyboard at request modal

This commit is contained in:
ardocrat
2024-04-21 20:42:01 +03:00
parent 1b7d96eff5
commit 792b64951a
43 changed files with 8 additions and 6 deletions
@@ -0,0 +1,168 @@
package mw.gri.android;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.os.*;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import java.util.List;
public class BackgroundService extends Service {
private static final String TAG = BackgroundService.class.getSimpleName();
private PowerManager.WakeLock mWakeLock;
private final Handler mHandler = new Handler(Looper.getMainLooper());
private boolean mStopped = false;
private static final int SYNC_STATUS_NOTIFICATION_ID = 1;
private NotificationCompat.Builder mNotificationBuilder;
private final Runnable mUpdateSyncStatus = new Runnable() {
@Override
public void run() {
if (mStopped) {
return;
}
// Update sync status at notification.
mNotificationBuilder.setContentText(getSyncStatusText());
NotificationManager manager = getSystemService(NotificationManager.class);
manager.notify(SYNC_STATUS_NOTIFICATION_ID, mNotificationBuilder.build());
// Send broadcast to MainActivity if exit from the app is needed after node stop.
if (exitAppAfterNodeStop()) {
sendBroadcast(new Intent(MainActivity.STOP_APP_ACTION));
mStopped = true;
}
// Repeat notification update if service is not stopped.
if (!mStopped) {
mHandler.postDelayed(this, 500);
}
}
};
@Override
public void onCreate() {
if (mStopped) {
return;
}
// Prevent CPU to sleep at background.
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
// Create channel to show notifications.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
TAG, TAG, NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
// Show notification with sync status.
Intent i = getPackageManager().getLaunchIntentForPackage(this.getPackageName());
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_IMMUTABLE);
mNotificationBuilder = new NotificationCompat.Builder(this, TAG)
.setContentTitle(this.getSyncTitle())
.setContentText(this.getSyncStatusText())
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent);
Notification notification = mNotificationBuilder.build();
// Start service at foreground state to prevent killing by system.
startForeground(SYNC_STATUS_NOTIFICATION_ID, notification);
// Update sync status at notification.
mHandler.post(mUpdateSyncStatus);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
onStop();
super.onTaskRemoved(rootIntent);
}
@Override
public void onDestroy() {
onStop();
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onStop() {
mStopped = true;
// Stop updating the notification.
mHandler.removeCallbacks(mUpdateSyncStatus);
// Remove service from foreground state.
stopForeground(Service.STOP_FOREGROUND_REMOVE);
// Remove notification.
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.deleteNotificationChannel(TAG);
}
notificationManager.cancel(SYNC_STATUS_NOTIFICATION_ID);
// Release wake lock to allow CPU to sleep at background.
if (mWakeLock.isHeld()) {
mWakeLock.release();
mWakeLock = null;
}
}
// Start the service.
public static void start(Context context) {
if (!isServiceRunning(context)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, BackgroundService.class));
} else {
context.startService(new Intent(context, BackgroundService.class));
}
}
}
// Stop the service.
public static void stop(Context context) {
context.stopService(new Intent(context, BackgroundService.class));
}
// Check if service is running.
private static boolean isServiceRunning(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(BackgroundService.class.getName())) {
return true;
}
}
return false;
}
// Get sync status text for notification from native code.
private native String getSyncStatusText();
// Get sync title text for notification from native code.
private native String getSyncTitle();
// Check if app from the app is needed after node stop from native code.
private native boolean exitAppAfterNodeStop();
}
@@ -0,0 +1,181 @@
package mw.gri.android;
import android.content.*;
import android.os.Bundle;
import android.os.Process;
import android.system.ErrnoException;
import android.system.Os;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import androidx.core.graphics.Insets;
import androidx.core.view.DisplayCutoutCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.androidgamesdk.GameActivity;
import static android.content.ClipDescription.MIMETYPE_TEXT_HTML;
import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN;
public class MainActivity extends GameActivity {
public static String STOP_APP_ACTION = "STOP_APP";
static {
System.loadLibrary("grim");
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent i) {
if (i.getAction().equals(STOP_APP_ACTION)) {
onExit();
Process.killProcess(Process.myPid());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// Setup HOME environment variable for native code configurations.
try {
Os.setenv("HOME", getExternalFilesDir("").getPath(), true);
} catch (ErrnoException e) {
throw new RuntimeException(e);
}
super.onCreate(null);
// Register receiver to finish activity from the BackgroundService.
registerReceiver(mBroadcastReceiver, new IntentFilter(STOP_APP_ACTION));
// Start notification service.
BackgroundService.start(this);
// Listener for display insets (cutouts) to pass values into native code.
View content = getWindow().getDecorView().findViewById(android.R.id.content);
ViewCompat.setOnApplyWindowInsetsListener(content, (v, insets) -> {
// Setup cutouts values.
DisplayCutoutCompat dc = insets.getDisplayCutout();
int cutoutTop = 0;
int cutoutRight = 0;
int cutoutBottom = 0;
int cutoutLeft = 0;
if (dc != null) {
cutoutTop = dc.getSafeInsetTop();
cutoutRight = dc.getSafeInsetRight();
cutoutBottom = dc.getSafeInsetBottom();
cutoutLeft = dc.getSafeInsetLeft();
}
// Get display insets.
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
// Setup values to pass into native code.
int[] values = new int[]{0, 0, 0, 0};
values[0] = Utils.pxToDp(Integer.max(cutoutTop, systemBars.top), this);
values[1] = Utils.pxToDp(Integer.max(cutoutRight, systemBars.right), this);
values[2] = Utils.pxToDp(Integer.max(cutoutBottom, systemBars.bottom), this);
values[3] = Utils.pxToDp(Integer.max(cutoutLeft, systemBars.left), this);
onDisplayInsets(values);
return insets;
});
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// To support non-english input.
if (event.getAction() == KeyEvent.ACTION_MULTIPLE && event.getKeyCode() == KeyEvent.KEYCODE_UNKNOWN) {
if (!event.getCharacters().isEmpty()) {
onInput(event.getCharacters());
return false;
}
// Pass any other input values into native code.
} else if (event.getAction() == KeyEvent.ACTION_UP &&
event.getKeyCode() != KeyEvent.KEYCODE_ENTER &&
event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
onInput(String.valueOf((char)event.getUnicodeChar()));
return false;
}
return super.dispatchKeyEvent(event);
}
// Provide last entered character from soft keyboard into native code.
public native void onInput(String character);
// Implemented into native code to handle display insets change.
native void onDisplayInsets(int[] cutouts);
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
// Implemented into native code to handle key code BACK event.
public native void onBack();
// Actions on app exit.
private void onExit() {
unregisterReceiver(mBroadcastReceiver);
BackgroundService.stop(this);
}
@Override
protected void onDestroy() {
onExit();
// Kill process after 3 seconds if app was terminated from recent apps to prevent app hanging.
new Thread(() -> {
try {
onTermination();
Thread.sleep(3000);
Process.killProcess(Process.myPid());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
// Destroy an app and kill process.
super.onDestroy();
Process.killProcess(Process.myPid());
}
// Notify native code to stop activity (e.g. node) if app was terminated from recent apps.
public native void onTermination();
// Called from native code to set text into clipboard.
public void copyText(String data) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(data, data);
clipboard.setPrimaryClip(clip);
}
// Called from native code to get text from clipboard.
public String pasteText() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
String text;
if (!(clipboard.hasPrimaryClip())) {
text = "";
} else if (!(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))
&& !(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_HTML))) {
text = "";
} else {
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
text = item.getText().toString();
}
return text;
}
public void showKeyboard() {
InputMethodManager imm = (InputMethodManager )getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);
}
public void hideKeyboard() {
InputMethodManager imm = (InputMethodManager )getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
}
}
@@ -0,0 +1,10 @@
package mw.gri.android;
import android.content.Context;
public class Utils {
// Convert Pixels to DensityPixels
public static int pxToDp(int px, Context context) {
return (int) (px / context.getResources().getDisplayMetrics().density);
}
}