initial work toward api 26+

* introduce notification channels
* always use foreground service on 26+
This commit is contained in:
Daniel Gultsch 2018-09-05 21:37:05 +02:00
parent d5b50d1076
commit 676d31f606
17 changed files with 1074 additions and 914 deletions

View File

@ -60,13 +60,13 @@ ext {
} }
android { android {
compileSdkVersion 27 compileSdkVersion 28
defaultConfig { defaultConfig {
minSdkVersion 19 minSdkVersion 19
targetSdkVersion 25 targetSdkVersion 28
versionCode 283 versionCode 283
versionName "2.2.9" versionName "2.3.0-alpha"
archivesBaseName += "-$versionName" archivesBaseName += "-$versionName"
applicationId "eu.siacs.conversations" applicationId "eu.siacs.conversations"
resValue "string", "applicationId", applicationId resValue "string", "applicationId", applicationId

View File

@ -13,4 +13,3 @@
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true # org.gradle.parallel=true
org.gradle.jvmargs=-Xmx2048M org.gradle.jvmargs=-Xmx2048M
org.gradle.configureondemand=false

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-4.10-all.zip

View File

@ -16,6 +16,7 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-feature <uses-feature
android:name="android.hardware.location" android:name="android.hardware.location"

View File

@ -14,6 +14,7 @@ import android.os.CancellationSignal;
import android.os.IBinder; import android.os.IBinder;
import android.os.ParcelFileDescriptor; import android.os.ParcelFileDescriptor;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log; import android.util.Log;
import com.google.zxing.BarcodeFormat; import com.google.zxing.BarcodeFormat;
@ -162,7 +163,6 @@ public class BarcodeProvider extends ContentProvider implements ServiceConnectio
synchronized (this) { synchronized (this) {
if (mXmppConnectionService == null && !mBindingInProcess) { if (mXmppConnectionService == null && !mBindingInProcess) {
Log.d(Config.LOGTAG, "calling to bind service"); Log.d(Config.LOGTAG, "calling to bind service");
context.startService(intent);
context.bindService(intent, this, Context.BIND_AUTO_CREATE); context.bindService(intent, this, Context.BIND_AUTO_CREATE);
this.mBindingInProcess = true; this.mBindingInProcess = true;
} }

View File

@ -12,6 +12,7 @@ import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
import android.service.chooser.ChooserTarget; import android.service.chooser.ChooserTarget;
import android.service.chooser.ChooserTargetService; import android.service.chooser.ChooserTargetService;
import android.support.v4.content.ContextCompat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -32,7 +33,6 @@ public class ContactChooserTargetService extends ChooserTargetService implements
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) { public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
Intent intent = new Intent(this, XmppConnectionService.class); Intent intent = new Intent(this, XmppConnectionService.class);
intent.setAction("contact_chooser"); intent.setAction("contact_chooser");
startService(intent);
bindService(intent, this, Context.BIND_AUTO_CREATE); bindService(intent, this, Context.BIND_AUTO_CREATE);
ArrayList<ChooserTarget> chooserTargets = new ArrayList<>(); ArrayList<ChooserTarget> chooserTargets = new ArrayList<>();
try { try {

View File

@ -3,38 +3,37 @@ package eu.siacs.conversations.services;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.util.Log; import android.util.Log;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.persistance.DatabaseBackend;
public class EventReceiver extends BroadcastReceiver { public class EventReceiver extends BroadcastReceiver {
public static final String SETTING_ENABLED_ACCOUNTS = "enabled_accounts"; public static final String SETTING_ENABLED_ACCOUNTS = "enabled_accounts";
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(final Context context, final Intent originalIntent) {
Intent mIntentForService = new Intent(context, XmppConnectionService.class); final Intent intentForService = new Intent(context, XmppConnectionService.class);
if (intent.getAction() != null) { if (originalIntent.getAction() != null) {
mIntentForService.setAction(intent.getAction()); intentForService.setAction(originalIntent.getAction());
} else { } else {
mIntentForService.setAction("other"); intentForService.setAction("other");
} }
final String action = intent.getAction(); final String action = originalIntent.getAction();
if (action.equals("ui") || hasEnabledAccounts(context)) { if (action.equals("ui") || hasEnabledAccounts(context)) {
try { try {
context.startService(mIntentForService); ContextCompat.startForegroundService(context, intentForService);
} catch (RuntimeException e) { } catch (RuntimeException e) {
Log.d(Config.LOGTAG,"EventReceiver was unable to start service"); Log.d(Config.LOGTAG,"EventReceiver was unable to start service");
} }
} else { } else {
Log.d(Config.LOGTAG,"EventReceiver ignored action "+mIntentForService.getAction()); Log.d(Config.LOGTAG,"EventReceiver ignored action "+intentForService.getAction());
} }
} }
public static boolean hasEnabledAccounts(Context context) { public static boolean hasEnabledAccounts(final Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SETTING_ENABLED_ACCOUNTS,true); return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SETTING_ENABLED_ACCOUNTS,true);
} }

View File

@ -42,14 +42,11 @@ public class ExportLogsService extends Service {
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
if (running.compareAndSet(false, true)) { if (running.compareAndSet(false, true)) {
new Thread(new Runnable() { new Thread(() -> {
@Override
public void run() {
export(); export();
stopForeground(true); stopForeground(true);
running.set(false); running.set(false);
stopSelf(); stopSelf();
}
}).start(); }).start();
} }
return START_NOT_STICKY; return START_NOT_STICKY;

View File

@ -1,16 +1,23 @@
package eu.siacs.conversations.services; package eu.siacs.conversations.services;
import android.app.Notification; import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.res.Resources; import android.content.res.Resources;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.media.AudioAttributes;
import android.media.RingtoneManager;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.SystemClock; import android.os.SystemClock;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.BigPictureStyle; import android.support.v4.app.NotificationCompat.BigPictureStyle;
import android.support.v4.app.NotificationCompat.Builder; import android.support.v4.app.NotificationCompat.Builder;
@ -25,7 +32,6 @@ import android.util.Log;
import android.util.Pair; import android.util.Pair;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -49,6 +55,7 @@ import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.ui.ConversationsActivity; import eu.siacs.conversations.ui.ConversationsActivity;
import eu.siacs.conversations.ui.ManageAccountActivity; import eu.siacs.conversations.ui.ManageAccountActivity;
import eu.siacs.conversations.ui.TimePreference; import eu.siacs.conversations.ui.TimePreference;
import eu.siacs.conversations.utils.Compatibility;
import eu.siacs.conversations.utils.GeoHelper; import eu.siacs.conversations.utils.GeoHelper;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
@ -58,26 +65,88 @@ public class NotificationService {
public static final Object CATCHUP_LOCK = new Object(); public static final Object CATCHUP_LOCK = new Object();
private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations"; private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
private final XmppConnectionService mXmppConnectionService;
private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024; private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
private static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
public static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
public static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4; public static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
public static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6; private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
private final XmppConnectionService mXmppConnectionService;
private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
private Conversation mOpenConversation; private Conversation mOpenConversation;
private boolean mIsInForeground; private boolean mIsInForeground;
private long mLastNotification; private long mLastNotification;
private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>(); NotificationService(final XmppConnectionService service) {
public NotificationService(final XmppConnectionService service) {
this.mXmppConnectionService = service; this.mXmppConnectionService = service;
} }
private static boolean displaySnoozeAction(List<Message> messages) {
int numberOfMessagesWithoutReply = 0;
for (Message message : messages) {
if (message.getStatus() == Message.STATUS_RECEIVED) {
++numberOfMessagesWithoutReply;
} else {
return false;
}
}
return numberOfMessagesWithoutReply >= 3;
}
public static Pattern generateNickHighlightPattern(final String nick) {
return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "\\b");
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void initializeChannels() {
final Context c = mXmppConnectionService;
NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
if (notificationManager == null) {
return;
}
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
c.getString(R.string.foreground_service_channel_name),
NotificationManager.IMPORTANCE_MIN);
foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description));
foregroundServiceChannel.setShowBadge(false);
foregroundServiceChannel.setGroup("status");
notificationManager.createNotificationChannel(foregroundServiceChannel);
final NotificationChannel errorChannel = new NotificationChannel("error",
c.getString(R.string.error_channel_name),
NotificationManager.IMPORTANCE_LOW);
errorChannel.setDescription(c.getString(R.string.error_channel_description));
errorChannel.setShowBadge(false);
errorChannel.setGroup("status");
notificationManager.createNotificationChannel(errorChannel);
final NotificationChannel messagesChannel = new NotificationChannel("messages",
c.getString(R.string.messages_channel_name),
NotificationManager.IMPORTANCE_HIGH);
messagesChannel.setShowBadge(true);
messagesChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build());
messagesChannel.setLightColor(0xff00ff00);
final int dat = 70;
final long[] pattern = {0, 3 * dat, dat, dat};
messagesChannel.setVibrationPattern(pattern);
messagesChannel.enableVibration(true);
messagesChannel.enableLights(true);
messagesChannel.setGroup("chats");
notificationManager.createNotificationChannel(messagesChannel);
final NotificationChannel silentMessagesChannel = new NotificationChannel("silent_messages",
c.getString(R.string.silent_messages_channel_name),
NotificationManager.IMPORTANCE_LOW);
silentMessagesChannel.setDescription(c.getString(R.string.silent_messages_channel_description));
silentMessagesChannel.setShowBadge(true);
silentMessagesChannel.setLightColor(0xff00ff00);
silentMessagesChannel.enableLights(true);
silentMessagesChannel.setGroup("chats");
notificationManager.createNotificationChannel(silentMessagesChannel);
}
public boolean notify(final Message message) { public boolean notify(final Message message) {
final Conversation conversation = (Conversation) message.getConversation(); final Conversation conversation = (Conversation) message.getConversation();
return message.getStatus() == Message.STATUS_RECEIVED return message.getStatus() == Message.STATUS_RECEIVED
@ -88,7 +157,7 @@ public class NotificationService {
; ;
} }
public boolean notificationsEnabled() { private boolean notificationsEnabled() {
return mXmppConnectionService.getBooleanPreference("show_notification", R.bool.show_notification); return mXmppConnectionService.getBooleanPreference("show_notification", R.bool.show_notification);
} }
@ -96,7 +165,7 @@ public class NotificationService {
return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers); return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
} }
public boolean isQuietHours() { private boolean isQuietHours() {
if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) { if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
return false; return false;
} }
@ -257,7 +326,7 @@ public class NotificationService {
updateNotification(notify, false); updateNotification(notify, false);
} }
public void updateNotification(final boolean notify, boolean summaryOnly) { private void updateNotification(final boolean notify, boolean summaryOnly) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService); final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
if (notifications.size() == 0) { if (notifications.size() == 0) {
@ -268,15 +337,16 @@ public class NotificationService {
} }
final Builder mBuilder; final Builder mBuilder;
if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mBuilder = buildSingleConversations(notifications.values().iterator().next()); mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify);
modifyForSoundVibrationAndLight(mBuilder, notify, preferences); modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
notify(NOTIFICATION_ID, mBuilder.build()); notify(NOTIFICATION_ID, mBuilder.build());
} else { } else {
mBuilder = buildMultipleConversation(); mBuilder = buildMultipleConversation(notify);
mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
modifyForSoundVibrationAndLight(mBuilder, notify, preferences); modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
if (!summaryOnly) { if (!summaryOnly) {
for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) { for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
Builder singleBuilder = buildSingleConversations(entry.getValue()); Builder singleBuilder = buildSingleConversations(entry.getValue(), notify);
singleBuilder.setGroup(CONVERSATIONS_GROUP); singleBuilder.setGroup(CONVERSATIONS_GROUP);
setNotificationColor(singleBuilder); setNotificationColor(singleBuilder);
notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build()); notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
@ -287,7 +357,6 @@ public class NotificationService {
} }
} }
private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) { private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
final Resources resources = mXmppConnectionService.getResources(); final Resources resources = mXmppConnectionService.getResources();
final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone)); final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
@ -328,9 +397,8 @@ public class NotificationService {
} }
} }
private Builder buildMultipleConversation() { private Builder buildMultipleConversation(final boolean notify) {
final Builder mBuilder = new NotificationCompat.Builder( final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, notify ? "messages" : "silent_messages");
mXmppConnectionService);
final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
style.setBigContentTitle(notifications.size() style.setBigContentTitle(notifications.size()
+ " " + " "
@ -376,8 +444,8 @@ public class NotificationService {
return mBuilder; return mBuilder;
} }
private Builder buildSingleConversations(final ArrayList<Message> messages) { private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify) {
final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService); final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, notify ? "messages" : "silent_messages");
if (messages.size() >= 1) { if (messages.size() >= 1) {
final Conversation conversation = (Conversation) messages.get(0).getConversation(); final Conversation conversation = (Conversation) messages.get(0).getConversation();
final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName().toString()); final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName().toString());
@ -471,18 +539,6 @@ public class NotificationService {
return mBuilder; return mBuilder;
} }
private static boolean displaySnoozeAction(List<Message> messages) {
int numberOfMessagesWithoutReply = 0;
for (Message message : messages) {
if (message.getStatus() == Message.STATUS_RECEIVED) {
++numberOfMessagesWithoutReply;
} else {
return false;
}
}
return numberOfMessagesWithoutReply >= 3;
}
private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder, private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
final Message message, final ArrayList<Message> messages) { final Message message, final ArrayList<Message> messages) {
try { try {
@ -674,7 +730,7 @@ public class NotificationService {
return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT); return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
} }
public PendingIntent createSnoozeIntent(Conversation conversation) { private PendingIntent createSnoozeIntent(Conversation conversation) {
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class); final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_SNOOZE); intent.setAction(XmppConnectionService.ACTION_SNOOZE);
intent.putExtra("uuid", conversation.getUuid()); intent.putExtra("uuid", conversation.getUuid());
@ -709,10 +765,6 @@ public class NotificationService {
} }
} }
public static Pattern generateNickHighlightPattern(final String nick) {
return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "\\b");
}
public void setOpenConversation(final Conversation conversation) { public void setOpenConversation(final Conversation conversation) {
this.mOpenConversation = conversation; this.mOpenConversation = conversation;
} }
@ -738,10 +790,9 @@ public class NotificationService {
} }
public Notification createForegroundNotification() { public Notification createForegroundNotification() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService); final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service)); mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
if (Config.SHOW_CONNECTED_ACCOUNTS) { if (Compatibility.twentySix() || Config.SHOW_CONNECTED_ACCOUNTS) {
List<Account> accounts = mXmppConnectionService.getAccounts(); List<Account> accounts = mXmppConnectionService.getAccounts();
int enabled = 0; int enabled = 0;
int connected = 0; int connected = 0;
@ -759,8 +810,14 @@ public class NotificationService {
} }
mBuilder.setContentIntent(createOpenConversationsIntent()); mBuilder.setContentIntent(createOpenConversationsIntent());
mBuilder.setWhen(0); mBuilder.setWhen(0);
mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN); mBuilder.setPriority(Notification.PRIORITY_LOW);
mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp); mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
if (Compatibility.twentySix()) {
mBuilder.setChannelId("foreground");
}
return mBuilder.build(); return mBuilder.build();
} }
@ -779,10 +836,10 @@ public class NotificationService {
errors.add(account); errors.add(account);
} }
} }
if (mXmppConnectionService.keepForegroundService()) { if (Compatibility.keepForegroundService(mXmppConnectionService)) {
notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification()); notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
} }
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService); final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
if (errors.size() == 0) { if (errors.size() == 0) {
cancel(ERROR_NOTIFICATION_ID); cancel(ERROR_NOTIFICATION_ID);
return; return;
@ -797,30 +854,37 @@ public class NotificationService {
mXmppConnectionService.getString(R.string.try_again), mXmppConnectionService.getString(R.string.try_again),
createTryAgainIntent()); createTryAgainIntent());
mBuilder.setDeleteIntent(createDismissErrorIntent()); mBuilder.setDeleteIntent(createDismissErrorIntent());
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp); mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
} else { } else {
mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning); mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
mBuilder.setLocalOnly(true); mBuilder.setLocalOnly(true);
mBuilder.setPriority(NotificationCompat.PRIORITY_LOW); }
mBuilder.setPriority(Notification.PRIORITY_LOW);
mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
145, 145,
new Intent(mXmppConnectionService, ManageAccountActivity.class), new Intent(mXmppConnectionService, ManageAccountActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT)); PendingIntent.FLAG_UPDATE_CURRENT));
if (Compatibility.twentySix()) {
mBuilder.setChannelId("error");
}
notify(ERROR_NOTIFICATION_ID, mBuilder.build()); notify(ERROR_NOTIFICATION_ID, mBuilder.build());
} }
public Notification updateFileAddingNotification(int current, Message message) { public void updateFileAddingNotification(int current, Message message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService); Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video)); mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
mBuilder.setProgress(100, current, false); mBuilder.setProgress(100, current, false);
mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp); mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
mBuilder.setContentIntent(createContentIntent(message.getConversation())); mBuilder.setContentIntent(createContentIntent(message.getConversation()));
if (Compatibility.twentySix()) {
mBuilder.setChannelId("foreground");
}
Notification notification = mBuilder.build(); Notification notification = mBuilder.build();
notify(FOREGROUND_NOTIFICATION_ID, notification); notify(FOREGROUND_NOTIFICATION_ID, notification);
return notification;
} }
private void notify(String tag, int id, Notification notification) { private void notify(String tag, int id, Notification notification) {

View File

@ -1,5 +1,6 @@
package eu.siacs.conversations.services; package eu.siacs.conversations.services;
import android.Manifest;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.app.AlarmManager; import android.app.AlarmManager;
@ -104,6 +105,7 @@ import eu.siacs.conversations.ui.SettingsActivity;
import eu.siacs.conversations.ui.UiCallback; import eu.siacs.conversations.ui.UiCallback;
import eu.siacs.conversations.ui.interfaces.OnAvatarPublication; import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable; import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
import eu.siacs.conversations.utils.Compatibility;
import eu.siacs.conversations.utils.ConversationsFileObserver; import eu.siacs.conversations.utils.ConversationsFileObserver;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.ExceptionHelper; import eu.siacs.conversations.utils.ExceptionHelper;
@ -157,7 +159,6 @@ public class XmppConnectionService extends Service {
public static final String ACTION_IDLE_PING = "idle_ping"; public static final String ACTION_IDLE_PING = "idle_ping";
public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh"; public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received"; public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp"; private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
@ -193,10 +194,9 @@ public class XmppConnectionService extends Service {
@Override @Override
public void onChange(boolean selfChange) { public void onChange(boolean selfChange) {
super.onChange(selfChange); super.onChange(selfChange);
Intent intent = new Intent(getApplicationContext(), if (restoredFromDatabaseLatch.getCount() == 0) {
XmppConnectionService.class); loadPhoneContacts();
intent.setAction(ACTION_MERGE_PHONE_CONTACTS); }
startService(intent);
} }
}; };
private FileBackend fileBackend = new FileBackend(this); private FileBackend fileBackend = new FileBackend(this);
@ -240,6 +240,7 @@ public class XmppConnectionService extends Service {
) { ) {
@Override @Override
public void onEvent(int event, String path) { public void onEvent(int event, String path) {
Log.d(Config.LOGTAG,"event "+event+" path="+path);
markFileDeleted(path); markFileDeleted(path);
} }
}; };
@ -569,11 +570,6 @@ public class XmppConnectionService extends Service {
resetAllAttemptCounts(true, false); resetAllAttemptCounts(true, false);
} }
break; break;
case ACTION_MERGE_PHONE_CONTACTS:
if (restoredFromDatabaseLatch.getCount() == 0) {
loadPhoneContacts();
}
return START_STICKY;
case Intent.ACTION_SHUTDOWN: case Intent.ACTION_SHUTDOWN:
logoutAndSave(true); logoutAndSave(true);
return START_NOT_STICKY; return START_NOT_STICKY;
@ -958,6 +954,9 @@ public class XmppConnectionService extends Service {
Resolver.init(this); Resolver.init(this);
this.mRandom = new SecureRandom(); this.mRandom = new SecureRandom();
updateMemorizingTrustmanager(); updateMemorizingTrustmanager();
if (Compatibility.twentySix()) {
mNotificationService.initializeChannels();
}
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8; final int cacheSize = maxMemory / 8;
this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) { this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
@ -984,7 +983,10 @@ public class XmppConnectionService extends Service {
restoreFromDatabase(); restoreFromDatabase();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
//TODO get this restarted if users gives permission
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver); getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(Config.LOGTAG, "starting file observer"); Log.d(Config.LOGTAG, "starting file observer");
new Thread(fileObserver::startWatching).start(); new Thread(fileObserver::startWatching).start();
@ -1062,7 +1064,7 @@ public class XmppConnectionService extends Service {
} }
public void toggleForegroundService() { public void toggleForegroundService() {
if (mForceForegroundService.get() || (keepForegroundService() && hasEnabledAccounts())) { if (mForceForegroundService.get() || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification()); startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
Log.d(Config.LOGTAG, "started foreground service"); Log.d(Config.LOGTAG, "started foreground service");
} else { } else {
@ -1071,14 +1073,11 @@ public class XmppConnectionService extends Service {
} }
} }
public boolean keepForegroundService() {
return getBooleanPreference(SettingsActivity.KEEP_FOREGROUND_SERVICE, R.bool.enable_foreground_service);
}
@Override @Override
public void onTaskRemoved(final Intent rootIntent) { public void onTaskRemoved(final Intent rootIntent) {
super.onTaskRemoved(rootIntent); super.onTaskRemoved(rootIntent);
if (keepForegroundService() || mForceForegroundService.get()) { //TODO check for accounts enabled
if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get()) {
Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated"); Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
} else { } else {
this.logoutAndSave(false); this.logoutAndSave(false);
@ -1951,6 +1950,7 @@ public class XmppConnectionService extends Service {
updateAccountUi(); updateAccountUi();
getNotificationService().updateErrorNotification(); getNotificationService().updateErrorNotification();
syncEnabledAccountSetting(); syncEnabledAccountSetting();
toggleForegroundService();
} }
} }

View File

@ -2,6 +2,7 @@ package eu.siacs.conversations.ui;
import android.preference.CheckBoxPreference; import android.preference.CheckBoxPreference;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.app.FragmentManager; import android.app.FragmentManager;
import android.content.DialogInterface; import android.content.DialogInterface;
@ -406,7 +407,7 @@ public class SettingsActivity extends XmppActivity implements
} }
private void startExport() { private void startExport() {
startService(new Intent(getApplicationContext(), ExportLogsService.class)); ContextCompat.startForegroundService(this, new Intent(this, ExportLogsService.class));
} }
private void displayToast(final String msg) { private void displayToast(final String msg) {

View File

@ -11,6 +11,7 @@ import android.widget.ListView;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.utils.Compatibility;
public class SettingsFragment extends PreferenceFragment { public class SettingsFragment extends PreferenceFragment {
@ -32,6 +33,7 @@ public class SettingsFragment extends PreferenceFragment {
mCategory.removePreference(cleanPrivateStorage); mCategory.removePreference(cleanPrivateStorage);
} }
} }
Compatibility.removeUnusedPreferences(this);
if (!TextUtils.isEmpty(page)) { if (!TextUtils.isEmpty(page)) {
openPreferenceScreen(page); openPreferenceScreen(page);

View File

@ -536,7 +536,11 @@ public abstract class XmppActivity extends ActionBarActivity {
intent.setAction(Intent.ACTION_SEND); intent.setAction(Intent.ACTION_SEND);
intent.setData(uri); intent.setData(uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startService(intent); startService(intent);
} catch (Exception e) {
Log.e(Config.LOGTAG,"unable to delegate uri permission",e);
}
} }
protected void inviteToConversation(Conversation conversation) { protected void inviteToConversation(Conversation conversation) {

View File

@ -0,0 +1,62 @@
package eu.siacs.conversations.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.support.annotation.BoolRes;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import eu.siacs.conversations.R;
import eu.siacs.conversations.ui.SettingsActivity;
import eu.siacs.conversations.ui.SettingsFragment;
public class Compatibility {
private static final List<String> UNUSED_SETTINGS_POST_TWENTYSIX = Arrays.asList(
SettingsActivity.KEEP_FOREGROUND_SERVICE,
"led",
"notification_ringtone",
"notification_headsup",
"vibrate_on_notification");
private static final List<String> UNUESD_SETTINGS_PRE_TWENTYSIX = Collections.singletonList("more_notification_settings");
public static boolean twentySix() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
private static boolean getBooleanPreference(Context context, String name, @BoolRes int res) {
return getPreferences(context).getBoolean(name, context.getResources().getBoolean(res));
}
private static SharedPreferences getPreferences(final Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static boolean keepForegroundService(Context context) {
return twentySix() || getBooleanPreference(context, SettingsActivity.KEEP_FOREGROUND_SERVICE, R.bool.enable_foreground_service);
}
public static void removeUnusedPreferences(SettingsFragment settingsFragment) {
List<PreferenceCategory> categories = Arrays.asList(
(PreferenceCategory) settingsFragment.findPreference("notification_category"),
(PreferenceCategory) settingsFragment.findPreference("other_expert_category"));
for (String key : (twentySix() ? UNUSED_SETTINGS_POST_TWENTYSIX : UNUESD_SETTINGS_PRE_TWENTYSIX)) {
Preference preference = settingsFragment.findPreference(key);
if (preference != null) {
for (PreferenceCategory category : categories) {
if (category != null) {
category.removePreference(preference);
}
}
}
}
}
}

View File

@ -2,12 +2,15 @@ package eu.siacs.conversations.utils;
import android.os.FileObserver; import android.os.FileObserver;
import android.util.Log;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Stack; import java.util.Stack;
import eu.siacs.conversations.Config;
/** /**
* Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2015 ownCloud Inc. * Copyright (C) 2015 ownCloud Inc.
@ -19,7 +22,7 @@ public abstract class ConversationsFileObserver {
private final String path; private final String path;
private final List<SingleFileObserver> mObservers = new ArrayList<>(); private final List<SingleFileObserver> mObservers = new ArrayList<>();
public ConversationsFileObserver(String path) { protected ConversationsFileObserver(String path) {
this.path = path; this.path = path;
} }
@ -83,13 +86,17 @@ public abstract class ConversationsFileObserver {
private class SingleFileObserver extends FileObserver { private class SingleFileObserver extends FileObserver {
private final String path; private final String path;
public SingleFileObserver(String path, int mask) { SingleFileObserver(String path, int mask) {
super(path, mask); super(path, mask);
this.path = path; this.path = path;
} }
@Override @Override
public void onEvent(int event, String filename) { public void onEvent(int event, String filename) {
if (filename == null) {
Log.d(Config.LOGTAG,"ignored file event with NULL filename (event="+event+")");
return;
}
ConversationsFileObserver.this.onEvent(event, path+'/'+filename); ConversationsFileObserver.this.onEvent(event, path+'/'+filename);
} }

View File

@ -727,4 +727,15 @@
<string name="conference_destroyed">This group chat has been destroyed</string> <string name="conference_destroyed">This group chat has been destroyed</string>
<string name="phone_book">Address book</string> <string name="phone_book">Address book</string>
<string name="unable_to_save_recording">Unable to save recording</string> <string name="unable_to_save_recording">Unable to save recording</string>
<string name="foreground_service_channel_name">Foreground service</string>
<string name="foreground_service_channel_description">This notification category is used to display a permanent notification indicating that Conversations is running.</string>
<string name="notification_group_status_information">Status Information</string>
<string name="error_channel_name">Connectivity Problems</string>
<string name="error_channel_description">This notification category is used to display a notification in case there is a problem connecting to an account.</string>
<string name="notification_group_messages">Messages</string>
<string name="messages_channel_name">Messages</string>
<string name="silent_messages_channel_name">Silent messages</string>
<string name="silent_messages_channel_description">This notification group is used to display notifications that should not trigger any sound. For example when being active on another device (Grace Period).</string>
<string name="pref_more_notification_settings">Notification Settings</string>
<string name="pref_more_notification_settings_summary">Importance, Sound, Vibrate</string>
</resources> </resources>

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="?attr/color_background_secondary" android:background="?attr/color_background_secondary"
android:key="main_screen"> android:key="main_screen">
@ -10,8 +9,7 @@
<PreferenceScreen <PreferenceScreen
android:key="huawei" android:key="huawei"
android:summary="@string/huawei_protected_apps_summary" android:summary="@string/huawei_protected_apps_summary"
android:title="@string/huawei_protected_apps" android:title="@string/huawei_protected_apps">
>
<intent <intent
android:targetClass="com.huawei.systemmanager.optimize.process.ProtectActivity" android:targetClass="com.huawei.systemmanager.optimize.process.ProtectActivity"
android:targetPackage="com.huawei.systemmanager" /> android:targetPackage="com.huawei.systemmanager" />
@ -24,8 +22,7 @@
android:entryValues="@array/omemo_setting_entry_values" android:entryValues="@array/omemo_setting_entry_values"
android:key="omemo" android:key="omemo"
android:summary="@string/pref_omemo_setting_summary_default_on" android:summary="@string/pref_omemo_setting_summary_default_on"
android:title="@string/pref_omemo_setting" android:title="@string/pref_omemo_setting" />
/>
<CheckBoxPreference <CheckBoxPreference
android:defaultValue="@bool/confirm_messages" android:defaultValue="@bool/confirm_messages"
android:key="confirm_messages" android:key="confirm_messages"
@ -43,7 +40,9 @@
android:summary="@string/pref_broadcast_last_activity_summary" android:summary="@string/pref_broadcast_last_activity_summary"
android:title="@string/pref_broadcast_last_activity" /> android:title="@string/pref_broadcast_last_activity" />
</PreferenceCategory> </PreferenceCategory>
<PreferenceCategory android:title="@string/pref_notification_settings"> <PreferenceCategory
android:title="@string/pref_notification_settings"
android:key="notification_category">
<CheckBoxPreference <CheckBoxPreference
android:defaultValue="@bool/show_notification" android:defaultValue="@bool/show_notification"
android:key="show_notification" android:key="show_notification"
@ -55,6 +54,20 @@
android:key="notifications_from_strangers" android:key="notifications_from_strangers"
android:summary="@string/pref_notifications_from_strangers_summary" android:summary="@string/pref_notifications_from_strangers_summary"
android:title="@string/pref_notifications_from_strangers" /> android:title="@string/pref_notifications_from_strangers" />
<PreferenceScreen
android:key="more_notification_settings"
android:dependency="show_notification"
android:summary="@string/pref_more_notification_settings_summary"
android:title="@string/pref_more_notification_settings">
<intent android:action="android.settings.CHANNEL_NOTIFICATION_SETTINGS">
<extra
android:name="android.provider.extra.APP_PACKAGE"
android:value="@string/applicationId" />
<extra
android:name="android.provider.extra.CHANNEL_ID"
android:value="messages" />
</intent>
</PreferenceScreen>
<CheckBoxPreference <CheckBoxPreference
android:defaultValue="@bool/headsup_notifications" android:defaultValue="@bool/headsup_notifications"
android:dependency="show_notification" android:dependency="show_notification"
@ -118,8 +131,7 @@
android:entryValues="@array/grace_periods_values" android:entryValues="@array/grace_periods_values"
android:key="grace_period_length" android:key="grace_period_length"
android:summary="@string/pref_notification_grace_period_summary" android:summary="@string/pref_notification_grace_period_summary"
android:title="@string/pref_notification_grace_period" android:title="@string/pref_notification_grace_period" />
/>
</PreferenceCategory> </PreferenceCategory>
<PreferenceCategory <PreferenceCategory
android:key="attachments" android:key="attachments"
@ -310,13 +322,14 @@
android:summary="@string/pref_treat_vibrate_as_dnd_summary" android:summary="@string/pref_treat_vibrate_as_dnd_summary"
android:title="@string/pref_treat_vibrate_as_silent" /> android:title="@string/pref_treat_vibrate_as_silent" />
</PreferenceCategory> </PreferenceCategory>
<PreferenceCategory android:title="@string/pref_expert_options_other"> <PreferenceCategory
android:key="other_expert_category"
android:title="@string/pref_expert_options_other">
<CheckBoxPreference <CheckBoxPreference
android:defaultValue="@bool/autojoin" android:defaultValue="@bool/autojoin"
android:key="autojoin" android:key="autojoin"
android:summary="@string/pref_autojoin_summary" android:summary="@string/pref_autojoin_summary"
android:title="@string/pref_autojoin" android:title="@string/pref_autojoin" />
/>
<CheckBoxPreference <CheckBoxPreference
android:defaultValue="@bool/indicate_received" android:defaultValue="@bool/indicate_received"
android:key="indicate_received" android:key="indicate_received"