2
0
mirror of https://github.com/KDE/kdeconnect-android synced 2025-08-22 18:07:55 +00:00

Make FindMyPhone plugin work on Android 10

This commit is contained in:
Erik Duisters 2020-01-05 17:40:54 +00:00
parent d4f35d8bd6
commit ad801f1db8
8 changed files with 258 additions and 64 deletions

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.kde.kdeconnect_tp" package="org.kde.kdeconnect_tp"
android:versionCode="11350" android:versionCode="11350"
android:versionName="1.13.5"> android:versionName="1.13.5">
@ -33,6 +34,7 @@
<uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<application <application
android:icon="@drawable/icon" android:icon="@drawable/icon"
@ -40,7 +42,8 @@
android:supportsRtl="true" android:supportsRtl="true"
android:allowBackup="false" android:allowBackup="false"
android:networkSecurityConfig="@xml/network_security_config" android:networkSecurityConfig="@xml/network_security_config"
android:theme="@style/KdeConnectTheme"> android:theme="@style/KdeConnectTheme"
android:name="org.kde.kdeconnect.MyApplication">
<service <service
android:name="org.kde.kdeconnect.BackgroundService" android:name="org.kde.kdeconnect.BackgroundService"
android:enabled="true" /> android:enabled="true" />
@ -119,6 +122,12 @@
android:label="@string/findmyphone_title" android:label="@string/findmyphone_title"
android:launchMode="singleInstance" /> android:launchMode="singleInstance" />
<receiver android:name="org.kde.kdeconnect.Plugins.FindMyPhonePlugin.FindMyPhoneReceiver">
<intent-filter>
<action android:name="org.kde.kdeconnect.Plugins.FindMyPhonePlugin.foundIt" />
</intent-filter>
</receiver>
<!-- Plugin-related activities and services --> <!-- Plugin-related activities and services -->
<activity <activity

View File

@ -6,7 +6,7 @@ buildscript {
google() google()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:3.5.2' classpath 'com.android.tools.build:gradle:3.5.3'
} }
} }
@ -82,6 +82,9 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.preference:preference:1.1.0' implementation 'androidx.preference:preference:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.lifecycle:lifecycle-runtime:2.1.0'
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
implementation 'androidx.lifecycle:lifecycle-common-java8:2.1.0'
implementation 'com.google.android.material:material:1.0.0' implementation 'com.google.android.material:material:1.0.0'
implementation 'com.jakewharton:disklrucache:2.0.2' //For caching album art bitmaps implementation 'com.jakewharton:disklrucache:2.0.2' //For caching album art bitmaps
implementation 'com.jaredrummler:android-device-names:1.1.9' //To get a human-friendly device name implementation 'com.jaredrummler:android-device-names:1.1.9' //To get a human-friendly device name

View File

@ -264,7 +264,7 @@
<string name="findmyphone_title_tablet">Find my tablet</string> <string name="findmyphone_title_tablet">Find my tablet</string>
<string name="findmyphone_title_tv">Find my TV</string> <string name="findmyphone_title_tv">Find my TV</string>
<string name="findmyphone_description">Rings this device so you can find it</string> <string name="findmyphone_description">Rings this device so you can find it</string>
<string name="findmyphone_found">Found</string> <string name="findmyphone_found">Found it</string>
<string name="open">Open</string> <string name="open">Open</string>
<string name="close">Close</string> <string name="close">Close</string>
@ -300,6 +300,7 @@
<string name="notification_channel_persistent">Persistent indicator</string> <string name="notification_channel_persistent">Persistent indicator</string>
<string name="notification_channel_media_control">Media control</string> <string name="notification_channel_media_control">Media control</string>
<string name="notification_channel_filetransfer">File transfer</string> <string name="notification_channel_filetransfer">File transfer</string>
<string name="notification_channel_high_priority">High priority</string>
<string name="mpris_stop">Stop the current player</string> <string name="mpris_stop">Stop the current player</string>
<string name="copy_url_to_clipboard">Copy URL to clipboard</string> <string name="copy_url_to_clipboard">Copy URL to clipboard</string>

View File

@ -18,6 +18,7 @@ public class NotificationHelper {
public final static String MEDIA_CONTROL = "media_control"; public final static String MEDIA_CONTROL = "media_control";
public final static String FILETRANSFER = "filetransfer"; public final static String FILETRANSFER = "filetransfer";
public final static String RECEIVENOTIFICATION = "receive"; public final static String RECEIVENOTIFICATION = "receive";
public final static String HIGHPRIORITY = "highpriority";
} }
public static void notifyCompat(NotificationManager notificationManager, int notificationId, Notification notification) { public static void notifyCompat(NotificationManager notificationManager, int notificationId, Notification notification) {
@ -80,6 +81,8 @@ public class NotificationHelper {
NotificationManager.IMPORTANCE_DEFAULT) NotificationManager.IMPORTANCE_DEFAULT)
); );
NotificationChannel highPriority = new NotificationChannel(Channels.HIGHPRIORITY, context.getString(R.string.notification_channel_high_priority), NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(highPriority);
} }

View File

@ -0,0 +1,41 @@
package org.kde.kdeconnect;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ProcessLifecycleOwner;
public class MyApplication extends Application {
private static class LifecycleObserver implements DefaultLifecycleObserver {
private boolean inForeground = false;
@Override
public void onStart(@NonNull LifecycleOwner owner) {
inForeground = true;
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
inForeground = false;
}
boolean isInForeground() {
return inForeground;
}
}
private static final LifecycleObserver foregroundTracker = new LifecycleObserver();
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(foregroundTracker);
}
public static boolean isInForeground() {
return foregroundTracker.isInForeground();
}
}

View File

@ -19,47 +19,37 @@
*/ */
package org.kde.kdeconnect.Plugins.FindMyPhonePlugin; package org.kde.kdeconnect.Plugins.FindMyPhonePlugin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log; import android.util.Log;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;
import org.kde.kdeconnect.BackgroundService;
import org.kde.kdeconnect.UserInterface.ThemeUtil; import org.kde.kdeconnect.UserInterface.ThemeUtil;
import org.kde.kdeconnect_tp.R; import org.kde.kdeconnect_tp.R;
public class FindMyPhoneActivity extends Activity { public class FindMyPhoneActivity extends AppCompatActivity {
static final String EXTRA_DEVICE_ID = "deviceId";
private MediaPlayer mediaPlayer; private String deviceId;
private int previousVolume; private FindMyPhonePlugin plugin;
private AudioManager audioManager;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mediaPlayer != null) {
// If this activity was already open and we received the ring packet again, just finish it
finish();
}
// otherwise the activity will become active again
}
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ThemeUtil.setUserPreferredTheme(this); ThemeUtil.setUserPreferredTheme(this);
setContentView(R.layout.activity_find_my_phone); setContentView(R.layout.activity_find_my_phone);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (!getIntent().hasExtra(EXTRA_DEVICE_ID)) {
Log.e("FindMyPhoneActivity", "You must include the deviceId for which this activity is started as an intent EXTRA");
finish();
}
deviceId = getIntent().getStringExtra(EXTRA_DEVICE_ID);
plugin = BackgroundService.getInstance().getDevice(deviceId).getPlugin(FindMyPhonePlugin.class);
Window window = this.getWindow(); Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
@ -72,42 +62,19 @@ public class FindMyPhoneActivity extends Activity {
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
/*
try { For whatever reason when Android launches this activity as a SystemAlertWindow it calls:
// Make sure we are heard even when the phone is silent, restore original volume later onCreate(), onStart(), onResume(), onStop(), onStart(), onResume().
previousVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM); When using BackgroundService.RunWithPlugin we get into concurrency problems and sometimes no sound will be played
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0); */
plugin.startPlaying();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); plugin.hideNotification();
Uri ringtone;
String ringtoneString = prefs.getString(getString(R.string.findmyphone_preference_key_ringtone), "");
if (ringtoneString.isEmpty()) {
ringtone = Settings.System.DEFAULT_RINGTONE_URI;
} else {
ringtone = Uri.parse(ringtoneString);
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, ringtone);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e("FindMyPhoneActivity", "Exception", e);
}
} }
@Override @Override
protected void onStop() { protected void onStop() {
super.onStop(); super.onStop();
if (mediaPlayer != null) { plugin.stopPlaying();
mediaPlayer.stop();
}
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, previousVolume, 0);
} }
} }

View File

@ -21,20 +21,46 @@
package org.kde.kdeconnect.Plugins.FindMyPhonePlugin; package org.kde.kdeconnect.Plugins.FindMyPhonePlugin;
import android.app.Activity; import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import org.kde.kdeconnect.Helpers.DeviceHelper; import org.kde.kdeconnect.Helpers.DeviceHelper;
import org.kde.kdeconnect.Helpers.NotificationHelper;
import org.kde.kdeconnect.MyApplication;
import org.kde.kdeconnect.NetworkPacket; import org.kde.kdeconnect.NetworkPacket;
import org.kde.kdeconnect.Plugins.Plugin; import org.kde.kdeconnect.Plugins.Plugin;
import org.kde.kdeconnect.Plugins.PluginFactory; import org.kde.kdeconnect.Plugins.PluginFactory;
import org.kde.kdeconnect.UserInterface.PluginSettingsFragment; import org.kde.kdeconnect.UserInterface.PluginSettingsFragment;
import org.kde.kdeconnect_tp.R; import org.kde.kdeconnect_tp.R;
import java.io.IOException;
import static android.content.Context.POWER_SERVICE;
@PluginFactory.LoadablePlugin @PluginFactory.LoadablePlugin
public class FindMyPhonePlugin extends Plugin { public class FindMyPhonePlugin extends Plugin {
public final static String PACKET_TYPE_FINDMYPHONE_REQUEST = "kdeconnect.findmyphone.request"; public final static String PACKET_TYPE_FINDMYPHONE_REQUEST = "kdeconnect.findmyphone.request";
private NotificationManager notificationManager;
private int notificationId;
private AudioManager audioManager;
private MediaPlayer mediaPlayer;
private int previousVolume;
private PowerManager powerManager;
@Override @Override
public String getDisplayName() { public String getDisplayName() {
switch (DeviceHelper.getDeviceType(context)) { switch (DeviceHelper.getDeviceType(context)) {
@ -55,13 +81,122 @@ public class FindMyPhonePlugin extends Plugin {
} }
@Override @Override
public boolean onPacketReceived(NetworkPacket np) { public boolean onCreate() {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationId = (int) System.currentTimeMillis();
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Uri ringtone;
String ringtoneString = prefs.getString(context.getString(R.string.findmyphone_preference_key_ringtone), "");
if (ringtoneString.isEmpty()) {
ringtone = Settings.System.DEFAULT_RINGTONE_URI;
} else {
ringtone = Uri.parse(ringtoneString);
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(context, ringtone);
//TODO: Deprecated use setAudioAttributes for API > 21
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} catch (Exception e) {
Log.e("FindMyPhoneActivity", "Exception", e);
return false;
}
Intent intent = new Intent(context, FindMyPhoneActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return true; return true;
}
@Override
public void onDestroy() {
stopPlaying();
audioManager = null;
mediaPlayer.release();
mediaPlayer = null;
}
@Override
public boolean onPacketReceived(NetworkPacket np) {
if (Build.VERSION.SDK_INT < 29 || MyApplication.isInForeground()) {
Intent intent = new Intent(context, FindMyPhoneActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(FindMyPhoneActivity.EXTRA_DEVICE_ID, device.getDeviceId());
context.startActivity(intent);
} else {
if (powerManager.isInteractive()) {
startPlaying();
showBroadcastNotification();
} else {
showActivityNotification();
}
}
return true;
}
private void showBroadcastNotification() {
Intent intent = new Intent(context, FindMyPhoneReceiver.class);
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
intent.setAction(FindMyPhoneReceiver.ACTION_FOUND_IT);
intent.putExtra(FindMyPhoneReceiver.EXTRA_DEVICE_ID, device.getDeviceId());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
createNotification(pendingIntent);
}
private void showActivityNotification() {
Intent intent = new Intent(context, FindMyPhoneActivity.class);
intent.putExtra(FindMyPhoneActivity.EXTRA_DEVICE_ID, device.getDeviceId());
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
createNotification(pi);
}
private void createNotification(PendingIntent pendingIntent) {
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, NotificationHelper.Channels.HIGHPRIORITY);
notification
.setSmallIcon(R.drawable.ic_notification)
.setOngoing(false)
.setFullScreenIntent(pendingIntent, true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentTitle(context.getString(R.string.findmyphone_found));
notification.setGroup("BackgroundService");
notificationManager.notify(notificationId, notification.build());
}
void startPlaying() {
if (!mediaPlayer.isPlaying()) {
// Make sure we are heard even when the phone is silent, restore original volume later
previousVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
mediaPlayer.start();
}
}
void hideNotification() {
notificationManager.cancel(notificationId);
}
void stopPlaying() {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, previousVolume, 0);
mediaPlayer.stop();
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
boolean isPlaying() {
return mediaPlayer.isPlaying();
} }
@Override @Override

View File

@ -0,0 +1,35 @@
package org.kde.kdeconnect.Plugins.FindMyPhonePlugin;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.kde.kdeconnect.BackgroundService;
public class FindMyPhoneReceiver extends BroadcastReceiver {
final static String ACTION_FOUND_IT = "org.kde.kdeconnect.Plugins.FindMyPhonePlugin.foundIt";
final static String EXTRA_DEVICE_ID = "deviceId";
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case ACTION_FOUND_IT:
foundIt(context, intent);
break;
default:
Log.d("ShareBroadcastReceiver", "Unhandled Action received: " + intent.getAction());
}
}
private void foundIt(Context context, Intent intent) {
if (!intent.hasExtra(EXTRA_DEVICE_ID)) {
Log.e("FindMyPhoneReceiver", "foundIt() - deviceId extra is not present, ignoring");
return;
}
String deviceId = intent.getStringExtra(EXTRA_DEVICE_ID);
BackgroundService.RunWithPlugin(context, deviceId, FindMyPhonePlugin.class, FindMyPhonePlugin::stopPlaying);
}
}