diff --git a/app/src/main/java/eu/faircode/email/ActivityEml.java b/app/src/main/java/eu/faircode/email/ActivityEml.java index fd2339ce4d..122bcf6e64 100644 --- a/app/src/main/java/eu/faircode/email/ActivityEml.java +++ b/app/src/main/java/eu/faircode/email/ActivityEml.java @@ -71,11 +71,9 @@ public class ActivityEml extends ActivityBase { Result result = new Result(); - InputStream is = null; - try { - ContentResolver resolver = context.getContentResolver(); - AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); - is = new BufferedInputStream(descriptor.createInputStream()); + ContentResolver resolver = context.getContentResolver(); + AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); + try (InputStream is = new BufferedInputStream(descriptor.createInputStream())) { Properties props = MessageHelper.getSessionProperties(Helper.AUTH_TYPE_PASSWORD, null, false); Session isession = Session.getInstance(props, null); @@ -112,9 +110,6 @@ public class ActivityEml extends ActivityBase { result.eml = new String(bos.toByteArray()); return result; - } finally { - if (is != null) - is.close(); } } diff --git a/app/src/main/java/eu/faircode/email/ActivitySetup.java b/app/src/main/java/eu/faircode/email/ActivitySetup.java index 8285f0b16b..eca03ea495 100644 --- a/app/src/main/java/eu/faircode/email/ActivitySetup.java +++ b/app/src/main/java/eu/faircode/email/ActivitySetup.java @@ -533,9 +533,7 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On ContentResolver resolver = context.getContentResolver(); DocumentFile file = DocumentFile.fromSingleUri(context, uri); - OutputStream raw = null; - try { - raw = new BufferedOutputStream(resolver.openOutputStream(uri)); + try (OutputStream raw = new BufferedOutputStream(resolver.openOutputStream(uri))) { Log.i("Writing URI=" + uri + " name=" + file.getName() + " virtual=" + file.isVirtual()); if (TextUtils.isEmpty(password)) @@ -564,9 +562,6 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On raw.flush(); Log.i("Exported data"); - } finally { - if (raw != null) - raw.close(); } return null; @@ -603,13 +598,11 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On throw new IllegalArgumentException(context.getString(R.string.title_no_stream)); } - InputStream raw = null; StringBuilder data = new StringBuilder(); - try { - Log.i("Reading URI=" + uri); - ContentResolver resolver = context.getContentResolver(); - AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); - raw = new BufferedInputStream(descriptor.createInputStream()); + Log.i("Reading URI=" + uri); + ContentResolver resolver = context.getContentResolver(); + AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); + try (InputStream raw = new BufferedInputStream(descriptor.createInputStream())) { InputStream in; if (TextUtils.isEmpty(password)) @@ -636,9 +629,6 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On String line; while ((line = reader.readLine()) != null) data.append(line); - } finally { - if (raw != null) - raw.close(); } Log.i("Importing data"); diff --git a/app/src/main/java/eu/faircode/email/ActivityView.java b/app/src/main/java/eu/faircode/email/ActivityView.java index e2b469e265..c7f3bda5b0 100644 --- a/app/src/main/java/eu/faircode/email/ActivityView.java +++ b/app/src/main/java/eu/faircode/email/ActivityView.java @@ -584,15 +584,10 @@ public class ActivityView extends ActivityBilling implements FragmentManager.OnB if (file.exists()) { StringBuilder sb = new StringBuilder(); try { - BufferedReader in = null; - try { - String line; - in = new BufferedReader(new FileReader(file)); + String line; + try (BufferedReader in = new BufferedReader(new FileReader(file))) { while ((line = in.readLine()) != null) sb.append(line).append("\r\n"); - } finally { - if (in != null) - in.close(); } return Helper.getDebugInfo(context, R.string.title_crash_info_remark, null, sb.toString()).id; @@ -740,25 +735,23 @@ public class ActivityView extends ActivityBilling implements FragmentManager.OnB List shortcuts = new ArrayList<>(); if (hasPermission(Manifest.permission.READ_CONTACTS)) { - Cursor cursor = null; - try { - // https://developer.android.com/guide/topics/providers/contacts-provider#ObsoleteData - cursor = getContentResolver().query( - ContactsContract.CommonDataKinds.Email.CONTENT_URI, - new String[]{ - ContactsContract.RawContacts._ID, - ContactsContract.Contacts.LOOKUP_KEY, - ContactsContract.Contacts.DISPLAY_NAME, - ContactsContract.CommonDataKinds.Email.DATA, - ContactsContract.Contacts.STARRED, - ContactsContract.Contacts.TIMES_CONTACTED, - ContactsContract.Contacts.LAST_TIME_CONTACTED - }, - ContactsContract.CommonDataKinds.Email.DATA + " <> ''", - null, - ContactsContract.Contacts.STARRED + " DESC" + - ", " + ContactsContract.Contacts.TIMES_CONTACTED + " DESC" + - ", " + ContactsContract.Contacts.LAST_TIME_CONTACTED + " DESC"); + // https://developer.android.com/guide/topics/providers/contacts-provider#ObsoleteData + try (Cursor cursor = getContentResolver().query( + ContactsContract.CommonDataKinds.Email.CONTENT_URI, + new String[]{ + ContactsContract.RawContacts._ID, + ContactsContract.Contacts.LOOKUP_KEY, + ContactsContract.Contacts.DISPLAY_NAME, + ContactsContract.CommonDataKinds.Email.DATA, + ContactsContract.Contacts.STARRED, + ContactsContract.Contacts.TIMES_CONTACTED, + ContactsContract.Contacts.LAST_TIME_CONTACTED + }, + ContactsContract.CommonDataKinds.Email.DATA + " <> ''", + null, + ContactsContract.Contacts.STARRED + " DESC" + + ", " + ContactsContract.Contacts.TIMES_CONTACTED + " DESC" + + ", " + ContactsContract.Contacts.LAST_TIME_CONTACTED + " DESC")) { while (cursor != null && cursor.moveToNext()) try { long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.RawContacts._ID)); @@ -801,9 +794,6 @@ public class ActivityView extends ActivityBilling implements FragmentManager.OnB } catch (Throwable ex) { Log.e(ex); } - } finally { - if (cursor != null) - cursor.close(); } } diff --git a/app/src/main/java/eu/faircode/email/AdapterMessage.java b/app/src/main/java/eu/faircode/email/AdapterMessage.java index e2a3395dc5..2f5d8274dd 100644 --- a/app/src/main/java/eu/faircode/email/AdapterMessage.java +++ b/app/src/main/java/eu/faircode/email/AdapterMessage.java @@ -1122,16 +1122,14 @@ public class AdapterMessage extends RecyclerView.Adapter'; EntityAttachment attachment = DB.getInstance(context).attachment().getAttachment(id, cid); if (attachment != null && attachment.available) { - InputStream is = null; - try { - File file = EntityAttachment.getFile(context, attachment.id); - - is = new BufferedInputStream(new FileInputStream(file)); + File file = EntityAttachment.getFile(context, attachment.id); + try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { byte[] bytes = new byte[(int) file.length()]; if (is.read(bytes) != bytes.length) throw new IOException("length"); @@ -1391,9 +1383,6 @@ public class AdapterMessage extends RecyclerView.Adapter" + "

"); - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(file)); + try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) { out.write(body); out.write(html); - } finally { - if (out != null) - out.close(); } refFile.delete(); @@ -1086,16 +1081,11 @@ public class FragmentCompose extends FragmentBase { File file1 = EntityAttachment.getFile(context, attachment1.id); - OutputStream os1 = null; - try { - byte[] bytes1 = encrypted.toByteArray(); - os1 = new BufferedOutputStream(new FileOutputStream(file1)); + byte[] bytes1 = encrypted.toByteArray(); + try (OutputStream os1 = new BufferedOutputStream(new FileOutputStream(file1))) { os1.write(bytes1); db.attachment().setDownloaded(attachment1.id, (long) bytes1.length); - } finally { - if (os1 != null) - os1.close(); } EntityAttachment attachment2 = new EntityAttachment(); @@ -1108,16 +1098,11 @@ public class FragmentCompose extends FragmentBase { File file2 = EntityAttachment.getFile(context, attachment2.id); - OutputStream os2 = null; - try { - byte[] bytes2 = key.getByteArrayExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE); - os2 = new BufferedOutputStream(new FileOutputStream(file2)); + byte[] bytes2 = key.getByteArrayExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE); + try (OutputStream os2 = new BufferedOutputStream(new FileOutputStream(file2))) { os2.write(bytes2); db.attachment().setDownloaded(attachment2.id, (long) bytes2.length); - } finally { - if (os2 != null) - os2.close(); } db.setTransactionSuccessful(); @@ -1357,17 +1342,12 @@ public class FragmentCompose extends FragmentBase { String name = uri.getLastPathSegment(); String s = null; - Cursor cursor = null; - try { - cursor = context.getContentResolver().query(uri, null, null, null, null, null); + try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null, null)) { if (cursor != null && cursor.moveToFirst()) { name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); s = cursor.getString(cursor.getColumnIndex(OpenableColumns.SIZE)); } - } finally { - if (cursor != null) - cursor.close(); } DB db = DB.getInstance(context); @@ -1456,16 +1436,12 @@ public class FragmentCompose extends FragmentBase { if (scaled != null) { Log.i("Image target size=" + scaled.getWidth() + "x" + scaled.getHeight()); - OutputStream out = null; - try { - out = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { scaled.compress("image/jpeg".equals(attachment.type) ? Bitmap.CompressFormat.JPEG : Bitmap.CompressFormat.PNG, REDUCED_IMAGE_QUALITY, out); } finally { - if (out != null) - out.close(); scaled.recycle(); } diff --git a/app/src/main/java/eu/faircode/email/FragmentIdentity.java b/app/src/main/java/eu/faircode/email/FragmentIdentity.java index f5792d5037..0e06c79bc4 100644 --- a/app/src/main/java/eu/faircode/email/FragmentIdentity.java +++ b/app/src/main/java/eu/faircode/email/FragmentIdentity.java @@ -618,8 +618,7 @@ public class FragmentIdentity extends FragmentBase { // Create transport String protocol = (starttls ? "smtp" : "smtps"); - Transport itransport = isession.getTransport(protocol); - try { + try (Transport itransport = isession.getTransport(protocol)) { try { itransport.connect(host, Integer.parseInt(port), user, password); } catch (AuthenticationFailedException ex) { @@ -629,8 +628,6 @@ public class FragmentIdentity extends FragmentBase { } else throw ex; } - } finally { - itransport.close(); } } diff --git a/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java b/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java index 3f2477c8ed..5e1455bb36 100644 --- a/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java +++ b/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java @@ -255,9 +255,7 @@ public class FragmentQuickSetup extends FragmentBase { Properties props = MessageHelper.getSessionProperties(auth_type, null, false); Session isession = Session.getInstance(props, null); isession.setDebug(true); - IMAPStore istore = null; - try { - istore = (IMAPStore) isession.getStore(provider.imap_starttls ? "imap" : "imaps"); + try (IMAPStore istore = (IMAPStore) isession.getStore(provider.imap_starttls ? "imap" : "imaps")) { istore.connect(provider.imap_host, provider.imap_port, user, password); separator = istore.getDefaultFolder().getSeparator(); @@ -295,9 +293,6 @@ public class FragmentQuickSetup extends FragmentBase { if (!inbox || !drafts) throw new IllegalArgumentException( context.getString(R.string.title_setup_no_settings, dparts[1])); - } finally { - if (istore != null) - istore.close(); } } @@ -305,11 +300,8 @@ public class FragmentQuickSetup extends FragmentBase { Properties props = MessageHelper.getSessionProperties(auth_type, null, false); Session isession = Session.getInstance(props, null); isession.setDebug(true); - Transport itransport = isession.getTransport(provider.smtp_starttls ? "smtp" : "smtps"); - try { + try (Transport itransport = isession.getTransport(provider.smtp_starttls ? "smtp" : "smtps")) { itransport.connect(provider.smtp_host, provider.smtp_port, user, password); - } finally { - itransport.close(); } } diff --git a/app/src/main/java/eu/faircode/email/FragmentRule.java b/app/src/main/java/eu/faircode/email/FragmentRule.java index f5a48c315d..d2f8284e4f 100644 --- a/app/src/main/java/eu/faircode/email/FragmentRule.java +++ b/app/src/main/java/eu/faircode/email/FragmentRule.java @@ -296,23 +296,18 @@ public class FragmentRule extends FragmentBase { } private void handlePickContact(Intent data) { - Cursor cursor = null; - try { - Uri uri = data.getData(); - if (uri != null) - cursor = getContext().getContentResolver().query(uri, - new String[]{ - ContactsContract.CommonDataKinds.Email.ADDRESS - }, - null, null, null); + Uri uri = data.getData(); + if (uri == null) return; + try (Cursor cursor = getContext().getContentResolver().query(uri, + new String[]{ + ContactsContract.CommonDataKinds.Email.ADDRESS + }, + null, null, null)) { if (cursor != null && cursor.moveToFirst()) etSender.setText(cursor.getString(0)); } catch (Throwable ex) { Log.e(ex); Helper.unexpectedError(getContext(), getViewLifecycleOwner(), ex); - } finally { - if (cursor != null) - cursor.close(); } } diff --git a/app/src/main/java/eu/faircode/email/Helper.java b/app/src/main/java/eu/faircode/email/Helper.java index e5e07ddeac..ae5ffcf434 100644 --- a/app/src/main/java/eu/faircode/email/Helper.java +++ b/app/src/main/java/eu/faircode/email/Helper.java @@ -489,10 +489,8 @@ public class Helper { attachment.progress = 0; attachment.id = db.attachment().insertAttachment(attachment); - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); @@ -502,9 +500,6 @@ public class Helper { size += write(os, key + "=" + settings.get(key) + "\r\n"); db.attachment().setDownloaded(attachment.id, size); - } finally { - if (os != null) - os.close(); } } @@ -520,10 +515,8 @@ public class Helper { attachment.progress = 0; attachment.id = db.attachment().insertAttachment(attachment); - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); @@ -538,9 +531,6 @@ public class Helper { } db.attachment().setDownloaded(attachment.id, size); - } finally { - if (os != null) - os.close(); } } @@ -556,10 +546,8 @@ public class Helper { log.progress = 0; log.id = db.attachment().insertAttachment(log); - OutputStream os = null; File file = EntityAttachment.getFile(context, log.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; long from = new Date().getTime() - 24 * 3600 * 1000L; @@ -569,9 +557,6 @@ public class Helper { size += write(os, String.format("%s %s\r\n", DF.format(entry.time), entry.data)); db.attachment().setDownloaded(log.id, size); - } finally { - if (os != null) - os.close(); } } @@ -587,10 +572,8 @@ public class Helper { attachment.progress = 0; attachment.id = db.attachment().insertAttachment(attachment); - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; DateFormat DF = SimpleDateFormat.getTimeInstance(); @@ -604,9 +587,6 @@ public class Helper { op.error)); db.attachment().setDownloaded(attachment.id, size); - } finally { - if (os != null) - os.close(); } } @@ -623,11 +603,8 @@ public class Helper { attachment.id = db.attachment().insertAttachment(attachment); Process proc = null; - BufferedReader br = null; - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { String[] cmd = new String[]{"logcat", "-d", @@ -635,20 +612,17 @@ public class Helper { //"-t", "1000", Log.TAG + ":I"}; proc = Runtime.getRuntime().exec(cmd); - br = new BufferedReader(new InputStreamReader(proc.getInputStream())); long size = 0; + try (BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { + String line; + while ((line = br.readLine()) != null) + size += write(os, line + "\r\n"); + } - String line; - while ((line = br.readLine()) != null) - size += write(os, line + "\r\n"); db.attachment().setDownloaded(attachment.id, size); } finally { - if (os != null) - os.close(); - if (br != null) - br.close(); if (proc != null) proc.destroy(); } @@ -683,20 +657,13 @@ public class Helper { } static void writeText(File file, String content) throws IOException { - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(file)); + try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) { out.write(content == null ? "" : content); - } finally { - if (out != null) - out.close(); } } static String readText(File file) throws IOException { - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); + try (BufferedReader in = new BufferedReader(new FileReader(file))) { StringBuilder body = new StringBuilder(); String line; while ((line = in.readLine()) != null) { @@ -704,26 +671,17 @@ public class Helper { body.append('\n'); } return body.toString(); - } finally { - if (in != null) - in.close(); } } static void copy(File src, File dst) throws IOException { - InputStream in = new BufferedInputStream(new FileInputStream(src)); - try { - OutputStream out = new BufferedOutputStream(new FileOutputStream(dst)); - try { + try (InputStream in = new BufferedInputStream(new FileInputStream(src))) { + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) { byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); - } finally { - out.close(); } - } finally { - in.close(); } } diff --git a/app/src/main/java/eu/faircode/email/HtmlHelper.java b/app/src/main/java/eu/faircode/email/HtmlHelper.java index d35986daec..ef1998eded 100644 --- a/app/src/main/java/eu/faircode/email/HtmlHelper.java +++ b/app/src/main/java/eu/faircode/email/HtmlHelper.java @@ -261,24 +261,16 @@ public class HtmlHelper { } try { - InputStream probe = null; BitmapFactory.Options options = new BitmapFactory.Options(); - try { - Log.i("Probe " + source); - probe = new URL(source).openStream(); + Log.i("Probe " + source); + try (InputStream probe = new URL(source).openStream()) { options.inJustDecodeBounds = true; BitmapFactory.decodeStream(probe, null, options); - } finally { - if (probe != null) - probe.close(); } + Log.i("Download " + source); Bitmap bm; - InputStream is = null; - try { - Log.i("Download " + source); - is = new URL(source).openStream(); - + try (InputStream is = new URL(source).openStream()) { int scaleTo = context.getResources().getDisplayMetrics().widthPixels; int factor = 1; while (options.outWidth / factor > scaleTo) @@ -291,9 +283,6 @@ public class HtmlHelper { bm = BitmapFactory.decodeStream(is, null, options); } else bm = BitmapFactory.decodeStream(is); - } finally { - if (is != null) - is.close(); } if (bm == null) @@ -301,13 +290,8 @@ public class HtmlHelper { Log.i("Downloaded image"); - OutputStream os = null; - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { bm.compress(Bitmap.CompressFormat.PNG, 90, os); - } finally { - if (os != null) - os.close(); } // Create drawable from bitmap diff --git a/app/src/main/java/eu/faircode/email/MessageHelper.java b/app/src/main/java/eu/faircode/email/MessageHelper.java index 704cf1a881..a4ce0ebfc9 100644 --- a/app/src/main/java/eu/faircode/email/MessageHelper.java +++ b/app/src/main/java/eu/faircode/email/MessageHelper.java @@ -34,6 +34,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; @@ -234,17 +235,12 @@ public class MessageHelper { if (attachment.available && EntityAttachment.PGP_SIGNATURE.equals(attachment.encryption)) { InternetAddress from = (InternetAddress) message.from[0]; File file = EntityAttachment.getFile(context, attachment.id); - BufferedReader br = null; StringBuilder sb = new StringBuilder(); - try { - br = new BufferedReader(new FileReader(file)); + try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) if (!line.startsWith("-----") && !line.endsWith("-----")) sb.append(line); - } finally { - if (br != null) - br.close(); } imessage.addHeader("Autocrypt", "addr=" + from.getAddress() + "; keydata=" + sb.toString()); @@ -624,13 +620,10 @@ public class MessageHelper { if (TextUtils.isEmpty(charset)) { if (BuildConfig.DEBUG) warnings.add(context.getString(R.string.title_no_charset, ct.toString())); - if (part.isMimeType("text/plain")) - try { - // The first 127 characters are the same as in US-ASCII - result = new String(result.getBytes("ISO-8859-1")); - } catch (UnsupportedEncodingException ex) { - warnings.add(Helper.formatThrowable(ex)); - } + if (part.isMimeType("text/plain")) { + // The first 127 characters are the same as in US-ASCII + result = new String(result.getBytes(StandardCharsets.ISO_8859_1)); + } } else { if ("US-ASCII".equals(Charset.forName(charset).name()) && !"US-ASCII".equals(charset.toUpperCase())) @@ -710,23 +703,21 @@ public class MessageHelper { File file = EntityAttachment.getFile(context, id); // Download attachment - OutputStream os = null; - try { - db.attachment().setProgress(id, null); - - InputStream is = apart.part.getInputStream(); - os = new BufferedOutputStream(new FileOutputStream(file)); - + db.attachment().setProgress(id, null); + try (InputStream is = apart.part.getInputStream()) { long size = 0; long total = apart.part.getSize(); - byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE]; - for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { - size += len; - os.write(buffer, 0, len); - - // Update progress - if (total > 0) - db.attachment().setProgress(id, (int) (size * 100 / total)); + + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { + byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE]; + for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { + size += len; + os.write(buffer, 0, len); + + // Update progress + if (total > 0) + db.attachment().setProgress(id, (int) (size * 100 / total)); + } } // Store attachment data @@ -739,9 +730,6 @@ public class MessageHelper { // Reset progress on failure db.attachment().setError(id, Helper.formatThrowable(ex)); return false; - } finally { - if (os != null) - os.close(); } } diff --git a/app/src/main/java/eu/faircode/email/ServiceExternal.java b/app/src/main/java/eu/faircode/email/ServiceExternal.java index cdb082804b..4be5b9a499 100644 --- a/app/src/main/java/eu/faircode/email/ServiceExternal.java +++ b/app/src/main/java/eu/faircode/email/ServiceExternal.java @@ -4,11 +4,11 @@ import android.app.Notification; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; -import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import androidx.annotation.Nullable; +import androidx.core.app.NotificationCompat; public class ServiceExternal extends Service { private final static String ACTION_ENABLE = "eu.faircode.email.ENABLE"; @@ -61,12 +61,8 @@ public class ServiceExternal extends Service { return null; } - private Notification.Builder getNotification() { - Notification.Builder builder; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - builder = new Notification.Builder(this, "service"); - else - builder = new Notification.Builder(this); + private NotificationCompat.Builder getNotification() { + NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "service"); builder .setSmallIcon(R.drawable.baseline_compare_arrows_white_24) @@ -75,7 +71,7 @@ public class ServiceExternal extends Service { .setShowWhen(false) .setPriority(Notification.PRIORITY_MIN) .setCategory(Notification.CATEGORY_STATUS) - .setVisibility(Notification.VISIBILITY_SECRET); + .setVisibility(NotificationCompat.VISIBILITY_SECRET); return builder; } diff --git a/app/src/main/java/eu/faircode/email/ServiceSynchronize.java b/app/src/main/java/eu/faircode/email/ServiceSynchronize.java index 6a7a5bf0a3..f23817c526 100644 --- a/app/src/main/java/eu/faircode/email/ServiceSynchronize.java +++ b/app/src/main/java/eu/faircode/email/ServiceSynchronize.java @@ -23,7 +23,6 @@ import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; -import android.app.Person; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -133,6 +132,7 @@ import javax.net.ssl.SSLException; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.core.app.NotificationCompat; import androidx.core.content.ContextCompat; import androidx.lifecycle.LifecycleService; import androidx.lifecycle.LiveData; @@ -450,7 +450,7 @@ public class ServiceSynchronize extends LifecycleService { return START_STICKY; } - private Notification.Builder getNotificationService(TupleAccountStats stats) { + private NotificationCompat.Builder getNotificationService(TupleAccountStats stats) { if (stats == null) stats = lastStats; if (stats == null) @@ -462,11 +462,7 @@ public class ServiceSynchronize extends LifecycleService { PendingIntent pi = PendingIntent.getService(this, PI_WHY, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Build notification - Notification.Builder builder; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - builder = new Notification.Builder(this, "service"); - else - builder = new Notification.Builder(this); + NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "service"); builder .setSmallIcon(R.drawable.baseline_compare_arrows_white_24) @@ -477,10 +473,10 @@ public class ServiceSynchronize extends LifecycleService { .setShowWhen(false) .setPriority(Notification.PRIORITY_MIN) .setCategory(Notification.CATEGORY_STATUS) - .setVisibility(Notification.VISIBILITY_SECRET); + .setVisibility(NotificationCompat.VISIBILITY_SECRET); if (stats.operations > 0) - builder.setStyle(new Notification.BigTextStyle().setSummaryText( + builder.setStyle(new NotificationCompat.BigTextStyle().setSummaryText( getResources().getQuantityString( R.plurals.title_notification_operations, stats.operations, stats.operations))); @@ -525,11 +521,7 @@ public class ServiceSynchronize extends LifecycleService { String channelName = (account == 0 ? "notification" : EntityAccount.getNotificationChannelName(account)); // Build public notification - Notification.Builder pbuilder; - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) - pbuilder = new Notification.Builder(this); - else - pbuilder = new Notification.Builder(this, channelName); + NotificationCompat.Builder pbuilder = new NotificationCompat.Builder(this, channelName); pbuilder .setSmallIcon(R.drawable.baseline_email_white_24) @@ -540,17 +532,13 @@ public class ServiceSynchronize extends LifecycleService { .setDeleteIntent(piClear) .setPriority(Notification.PRIORITY_DEFAULT) .setCategory(Notification.CATEGORY_STATUS) - .setVisibility(Notification.VISIBILITY_PUBLIC); + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); if (!TextUtils.isEmpty(accountName)) pbuilder.setSubText(accountName); // Build notification - Notification.Builder builder; - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) - builder = new Notification.Builder(this); - else - builder = new Notification.Builder(this, channelName); + NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelName); builder .setSmallIcon(R.drawable.baseline_email_white_24) @@ -584,7 +572,7 @@ public class ServiceSynchronize extends LifecycleService { builder.setOnlyAlertOnce(true); } else - builder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN); + builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN); if (pro) { DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); @@ -597,7 +585,7 @@ public class ServiceSynchronize extends LifecycleService { sb.append("
"); } - builder.setStyle(new Notification.BigTextStyle() + builder.setStyle(new NotificationCompat.BigTextStyle() .bigText(HtmlHelper.fromHtml(sb.toString())) .setSummaryText(title)); } @@ -636,26 +624,23 @@ public class ServiceSynchronize extends LifecycleService { PendingIntent piTrash = PendingIntent.getService(this, PI_TRASH, trash, PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Action.Builder actionSeen = new Notification.Action.Builder( + NotificationCompat.Action.Builder actionSeen = new NotificationCompat.Action.Builder( R.drawable.baseline_visibility_24, getString(R.string.title_action_seen), piSeen); - Notification.Action.Builder actionArchive = new Notification.Action.Builder( + NotificationCompat.Action.Builder actionArchive = new NotificationCompat.Action.Builder( R.drawable.baseline_archive_24, getString(R.string.title_action_archive), piArchive); - Notification.Action.Builder actionTrash = new Notification.Action.Builder( + NotificationCompat.Action.Builder actionTrash = new NotificationCompat.Action.Builder( R.drawable.baseline_delete_24, getString(R.string.title_action_trash), piTrash); - Notification.Builder mbuilder; - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) - mbuilder = new Notification.Builder(this); - else - mbuilder = new Notification.Builder(this, channelName); + NotificationCompat.Builder mbuilder; + mbuilder = new NotificationCompat.Builder(this, channelName); String folderName = message.folderDisplay == null ? Helper.localizeFolderName(this, message.folderName) @@ -702,32 +687,25 @@ public class ServiceSynchronize extends LifecycleService { sb.append(text); sb.append(""); } - mbuilder.setStyle(new Notification.BigTextStyle().bigText(HtmlHelper.fromHtml(sb.toString()))); + mbuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(HtmlHelper.fromHtml(sb.toString()))); } catch (IOException ex) { Log.e(ex); - mbuilder.setStyle(new Notification.BigTextStyle().bigText(ex.toString())); + mbuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(ex.toString())); } if (info.hasPhoto()) mbuilder.setLargeIcon(info.getPhotoBitmap()); if (info.hasLookupUri()) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) - mbuilder.addPerson(new Person.Builder() - .setUri(info.getLookupUri().toString()) - .build()); - else - mbuilder.addPerson(info.getLookupUri().toString()); + mbuilder.addPerson(info.getLookupUri().toString()); if (message.accountColor != null) { mbuilder.setColor(message.accountColor); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - mbuilder.setColorized(true); + mbuilder.setColorized(true); } } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - mbuilder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN); + mbuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN); notifications.add(mbuilder.build()); } @@ -735,11 +713,11 @@ public class ServiceSynchronize extends LifecycleService { return notifications; } - private Notification.Builder getNotificationError(String title, Throwable ex) { + private NotificationCompat.Builder getNotificationError(String title, Throwable ex) { return getNotificationError("error", title, ex, true); } - private Notification.Builder getNotificationError(String channel, String title, Throwable ex, boolean debug) { + private NotificationCompat.Builder getNotificationError(String channel, String title, Throwable ex, boolean debug) { // Build pending intent Intent intent = new Intent(this, ActivitySetup.class); if (debug) @@ -749,11 +727,7 @@ public class ServiceSynchronize extends LifecycleService { this, ActivitySetup.REQUEST_ERROR, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Build notification - Notification.Builder builder; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - builder = new Notification.Builder(this, channel); - else - builder = new Notification.Builder(this); + NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channel); builder .setSmallIcon(R.drawable.baseline_warning_white_24) @@ -765,9 +739,9 @@ public class ServiceSynchronize extends LifecycleService { .setPriority(Notification.PRIORITY_MAX) .setOnlyAlertOnce(true) .setCategory(Notification.CATEGORY_ERROR) - .setVisibility(Notification.VISIBILITY_SECRET); + .setVisibility(NotificationCompat.VISIBILITY_SECRET); - builder.setStyle(new Notification.BigTextStyle() + builder.setStyle(new NotificationCompat.BigTextStyle() .bigText(Helper.formatThrowable(ex, false, "\n"))); return builder; @@ -1755,14 +1729,9 @@ public class ServiceSynchronize extends LifecycleService { if (!file.exists()) throw new IllegalArgumentException("raw message file not found"); - InputStream is = null; - try { - Log.i(folder.name + " reading " + file); - is = new BufferedInputStream(new FileInputStream(file)); + Log.i(folder.name + " reading " + file); + try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { imessage = new MimeMessage(isession, is); - } finally { - if (is != null) - is.close(); } } @@ -1987,8 +1956,7 @@ public class ServiceSynchronize extends LifecycleService { // Create transport // TODO: cache transport? - Transport itransport = isession.getTransport(ident.getProtocol()); - try { + try (Transport itransport = isession.getTransport(ident.getProtocol())) { // Connect transport db.identity().setIdentityState(ident.id, "connecting"); try { @@ -2115,11 +2083,7 @@ public class ServiceSynchronize extends LifecycleService { throw ex; } finally { - try { - itransport.close(); - } finally { - db.identity().setIdentityState(ident.id, null); - } + db.identity().setIdentityState(ident.id, null); } } @@ -2143,14 +2107,9 @@ public class ServiceSynchronize extends LifecycleService { File file = EntityMessage.getRawFile(this, message.id); - OutputStream os = null; - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { imessage.writeTo(os); db.message().setMessageRaw(message.id, true); - } finally { - if (os != null) - os.close(); } }