From 236b76188a6faf381b91e2a9097177c1a9b62bb5 Mon Sep 17 00:00:00 2001 From: tom79 Date: Tue, 12 Sep 2017 18:14:41 +0200 Subject: [PATCH 1/8] Service binder --- .../mastodon/services/StreamingService.java | 31 ++++------------- .../activities/MainActivity.java | 34 +++++++++++++++++++ 2 files changed, 40 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java index 6c26e9683..830196fdb 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java @@ -22,6 +22,7 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; +import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.os.StrictMode; @@ -97,38 +98,18 @@ public class StreamingService extends Service { DELETE, NONE } + private final IBinder iBinder = new StreamingServiceBinder(); - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - if( intent != null){ - String accountId = intent.getStringExtra("accountId"); - String accountAcct = intent.getStringExtra("accountAcct"); - if( accountId != null && accountAcct != null){ - SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(getApplicationContext(), db).getAccountByIDAcct(accountId, accountAcct); - if( account != null) - callAsynchronousTask(account); - }else { - SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - List accounts = new AccountDAO(getApplicationContext(), db).getAllAccount(); - if( accounts != null){ - for (Account account: accounts) { - intent = new Intent(getApplicationContext(), StreamingService.class); - intent.putExtra("accountId", account.getId()); - intent.putExtra("accountAcct", account.getAcct()); - startService(intent); - } - } - } + public class StreamingServiceBinder extends Binder { + public StreamingService getService() { + return StreamingService.this; } - return START_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { - return null; + return iBinder; } diff --git a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index 20f7f9061..c4126b554 100644 --- a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -16,10 +16,12 @@ package fr.gouv.etalab.mastodon.activities; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; +import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; +import android.content.ServiceConnection; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; @@ -27,6 +29,8 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; +import android.os.IBinder; +import android.os.Messenger; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; @@ -903,6 +907,36 @@ public class MainActivity extends AppCompatActivity new UpdateAccountInfoByIDAsyncTask(getApplicationContext(), MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } + + StreamingService streamingService = null; + boolean mBound = false; + private ServiceConnection serviceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName className, IBinder service) { + StreamingService.StreamingServiceBinder binder = (StreamingService.StreamingServiceBinder) service; + streamingService = binder.getService(); + mBound = true; + } + @Override + public void onServiceDisconnected(ComponentName arg0) { + mBound = false; + } + }; + @Override + protected void onStart() { + super.onStart(); + Intent intent = new Intent(this, StreamingService.class); + bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); + } + @Override + protected void onStop() { + super.onStop(); + if (mBound) { + unbindService(serviceConnection); + mBound = false; + } + } + @Override protected void onPause() { super.onPause(); From 0fc3214390103f9ad90ac426eb56e98343a638fd Mon Sep 17 00:00:00 2001 From: tom79 Date: Tue, 12 Sep 2017 18:41:13 +0200 Subject: [PATCH 2/8] Removes useless methodes --- .../mastodon/services/StreamingService.java | 282 ++---------------- .../activities/MainActivity.java | 8 + 2 files changed, 41 insertions(+), 249 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java index 830196fdb..b41510665 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java @@ -19,34 +19,15 @@ import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.database.sqlite.SQLiteDatabase; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; import android.os.Binder; -import android.os.Build; import android.os.IBinder; -import android.os.StrictMode; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; -import android.text.Html; -import android.util.Log; -import android.view.View; - -import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; -import com.nostra13.universalimageloader.core.DisplayImageOptions; -import com.nostra13.universalimageloader.core.ImageLoader; -import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; -import com.nostra13.universalimageloader.core.assist.FailReason; -import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; -import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; - import org.json.JSONException; import org.json.JSONObject; - import java.io.BufferedInputStream; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -54,29 +35,14 @@ import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import javax.net.ssl.HttpsURLConnection; - -import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Notification; import fr.gouv.etalab.mastodon.client.Entities.Status; -import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.client.TLSSocketFactory; import fr.gouv.etalab.mastodon.helper.Helper; -import fr.gouv.etalab.mastodon.sqlite.AccountDAO; -import fr.gouv.etalab.mastodon.sqlite.Sqlite; -import mastodon.etalab.gouv.fr.mastodon.R; -import static fr.gouv.etalab.mastodon.helper.Helper.HOME_TIMELINE_INTENT; -import static fr.gouv.etalab.mastodon.helper.Helper.INTENT_ACTION; -import static fr.gouv.etalab.mastodon.helper.Helper.NOTIFICATION_INTENT; -import static fr.gouv.etalab.mastodon.helper.Helper.PREF_KEY_ID; -import static fr.gouv.etalab.mastodon.helper.Helper.canNotify; -import static fr.gouv.etalab.mastodon.helper.Helper.notify_user; /** * Created by Thomas on 28/08/2017. @@ -85,12 +51,10 @@ import static fr.gouv.etalab.mastodon.helper.Helper.notify_user; public class StreamingService extends Service { - private String message; - private int notificationId; - private Intent intent; - private String lastPreviousContent; - private static HashMap connectionHashMap = new HashMap<>(); - private static HashMap isConnectingHashMap = new HashMap<>(); + + private boolean isConnectingHashMap = false; + private HttpsURLConnection httpsURLConnection; + private EventStreaming lastEvent; public enum EventStreaming{ UPDATE, @@ -113,10 +77,16 @@ public class StreamingService extends Service { } + public void disconnect(){ + if( httpsURLConnection != null) + httpsURLConnection.disconnect(); + } + + /** * Task in background starts here. */ - private void callAsynchronousTask(final Account account) { + public void connect(final Account account) { //If an Internet connection and user agrees with notification refresh final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); //Check which notifications the user wants to see @@ -132,7 +102,7 @@ public class StreamingService extends Service { if(!Helper.isLoggedIn(getApplicationContext())) return; //If WIFI only and on WIFI OR user defined any connections to use the service. - if( isConnectingHashMap.get(account.getAcct()+account.getId()) != null && isConnectingHashMap.get(account.getAcct()+account.getId())) + if( isConnectingHashMap) return; if(!sharedpreferences.getBoolean(Helper.SET_WIFI_ONLY, false) || Helper.isOnWIFI(getApplicationContext())) { Thread readThread = new Thread(new Runnable() { @@ -140,30 +110,28 @@ public class StreamingService extends Service { public void run() { try { boolean connectionAlive = false; - isConnectingHashMap.put(account.getAcct()+account.getId(), true); - if( connectionHashMap.get(account.getAcct()+account.getId()) != null) { + isConnectingHashMap = true; + if( httpsURLConnection != null) { try { - connectionAlive = (connectionHashMap.get(account.getAcct()+account.getId()).getResponseCode() == 200); + connectionAlive = (httpsURLConnection.getResponseCode() == 200); } catch (Exception e) { connectionAlive = false; } } if( connectionAlive) { - HttpsURLConnection httpsURLConnection = connectionHashMap.get(account.getAcct() + account.getId()); if( httpsURLConnection != null) httpsURLConnection.disconnect(); } try { URL url = new URL("https://" + account.getInstance() + "/api/v1/streaming/user"); - HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); - urlConnection.setRequestProperty("Content-Type", "application/json"); - urlConnection.setRequestProperty("Authorization", "Bearer " + account.getToken()); - urlConnection.setRequestProperty("Connection", "Keep-Alive"); - urlConnection.setRequestProperty("Keep-Alive", "header"); - urlConnection.setRequestProperty("Connection", "close"); - urlConnection.setSSLSocketFactory(new TLSSocketFactory()); - connectionHashMap.put(account.getAcct()+account.getId(), urlConnection); - InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream()); + httpsURLConnection = (HttpsURLConnection) url.openConnection(); + httpsURLConnection.setRequestProperty("Content-Type", "application/json"); + httpsURLConnection.setRequestProperty("Authorization", "Bearer " + account.getToken()); + httpsURLConnection.setRequestProperty("Connection", "Keep-Alive"); + httpsURLConnection.setRequestProperty("Keep-Alive", "header"); + httpsURLConnection.setRequestProperty("Connection", "close"); + httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory()); + InputStream inputStream = new BufferedInputStream(httpsURLConnection.getInputStream()); readStream(inputStream, account); } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); @@ -180,16 +148,13 @@ public class StreamingService extends Service { - - - @SuppressWarnings("ConstantConditions") private String readStream(InputStream inputStream, final Account account) { BufferedReader reader = null; try{ reader = new BufferedReader(new InputStreamReader(inputStream)); String event; - EventStreaming eventStreaming = null; + EventStreaming eventStreaming; //noinspection InfiniteLoopStatement while(true){ try { @@ -233,7 +198,7 @@ public class StreamingService extends Service { lastEvent = EventStreaming.NONE; try { JSONObject eventJson = new JSONObject(event); - onRetrieveStreaming(eventStreaming, eventJson, account.getAcct(), account.getId()); + onRetrieveStreaming(eventStreaming, eventJson, account.getId()); } catch (JSONException e) { e.printStackTrace(); } @@ -256,7 +221,7 @@ public class StreamingService extends Service { } private void forceRestart(Account account){ - isConnectingHashMap.put(account.getAcct()+account.getId(), false); + isConnectingHashMap = false; SystemClock.sleep(1000); Intent intent = new Intent(getApplicationContext(), StreamingService.class); intent.putExtra("accountId", account.getId()); @@ -274,100 +239,21 @@ public class StreamingService extends Service { } - public void onRetrieveStreaming(EventStreaming event, JSONObject response, String acct, String userId) { + public void onRetrieveStreaming(EventStreaming event, JSONObject response, String userId) { if( response == null ) return; - final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - boolean notif_follow = sharedpreferences.getBoolean(Helper.SET_NOTIF_FOLLOW, true); - boolean notif_add = sharedpreferences.getBoolean(Helper.SET_NOTIF_ADD, true); - boolean notif_mention = sharedpreferences.getBoolean(Helper.SET_NOTIF_MENTION, true); - boolean notif_share = sharedpreferences.getBoolean(Helper.SET_NOTIF_SHARE, true); - //No previous notifications in cache, so no notification will be sent - boolean notify = false; - String notificationUrl = null; - String title = null; - Status status = null; - Notification notification = null; + Status status ; + Notification notification; String dataId = null; if( event == EventStreaming.NOTIFICATION){ notification = API.parseNotificationResponse(getApplicationContext(), response); - switch (notification.getType()){ - case "mention": - if(notif_mention){ - lastPreviousContent = notification.getStatus().getContent(); - notify = true; - notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getString(R.string.notif_mention)); - else - title = String.format("%s %s", notification.getAccount().getUsername(),getString(R.string.notif_mention)); - } - break; - case "reblog": - if(notif_share){ - notify = true; - notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getString(R.string.notif_reblog)); - else - title = String.format("%s %s", notification.getAccount().getUsername(),getString(R.string.notif_reblog)); - } - break; - case "favourite": - if(notif_add){ - notify = true; - notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getString(R.string.notif_favourite)); - else - title = String.format("%s %s", notification.getAccount().getUsername(),getString(R.string.notif_favourite)); - } - break; - case "follow": - if(notif_follow){ - notify = true; - notificationUrl = notification.getAccount().getAvatar(); - if( notification.getAccount().getDisplay_name() != null && notification.getAccount().getDisplay_name().length() > 0 ) - title = String.format("%s %s", Helper.shortnameToUnicode(notification.getAccount().getDisplay_name(), true),getString(R.string.notif_follow)); - else - title = String.format("%s %s", notification.getAccount().getUsername(),getString(R.string.notif_follow)); - } - break; - default: - break; - } Helper.cacheNotifications(getApplicationContext(), notification, userId); - if( notification.getStatus().getContent()!= null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - message = Html.fromHtml(notification.getStatus().getContent(), Html.FROM_HTML_MODE_LEGACY).toString(); - else - //noinspection deprecation - message = Html.fromHtml(notification.getStatus().getContent()).toString(); - message = message.substring(0, message.length()>49?49:message.length()); - message = message + "…"; - }else{ - message = ""; - } - }else if ( event == EventStreaming.UPDATE){ status = API.parseStatuses(getApplicationContext(), response); - status.setReplies(new ArrayList()); //Force to don't display replies + status.setReplies(new ArrayList()); status.setNew(true); Helper.cacheStatus(getApplicationContext(), status, userId); - if( status.getContent() != null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - message = Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY).toString(); - else - //noinspection deprecation - message = Html.fromHtml(status.getContent()).toString(); - message = message.substring(0, message.length()>49?49:message.length()); - message = message + "…"; - }else{ - message = ""; - } - title = getString(R.string.notif_pouet, status.getAccount().getUsername()); - notificationUrl = status.getAccount().getAvatar(); }else if( event == EventStreaming.DELETE){ try { dataId = response.getString("id"); @@ -375,110 +261,8 @@ public class StreamingService extends Service { e.printStackTrace(); } } - - //Check which user is connected and if activity is to front - boolean activityVisible = false; - try{ - activityVisible = MainActivity.isActivityVisible(); - }catch (Exception ignored){} - String connectedUser = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(getApplicationContext(), db).getAccountByID(connectedUser); - //User receiving the notification is connected - if( isCurrentAccountLoggedIn(acct, userId)){ - notify = false; - Intent intentBC = new Intent(Helper.RECEIVE_DATA); - intentBC.putExtra("eventStreaming", event); - LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBC); - } - //User receiving the notification is connected and application is to front, notification won't be pushed - //Instead, the interaction is done in the activity - if( activityVisible && isCurrentAccountLoggedIn(acct, userId)){ - notify = false; - }else if(event == EventStreaming.NOTIFICATION ){ - notify = true; - }else if(event == EventStreaming.UPDATE ){ - //lastPreviousContent contains the content of the last notification, if it was a mention it will avoid to push two notifications - if( account == null || (lastPreviousContent != null && lastPreviousContent.equals(status.getContent()))) { - notify = false; - }else { - notify = true; - //Retrieve users in db that owner has, and if the toot matches one of them we don't notify - List accounts = new AccountDAO(getApplicationContext(),db).getAllAccount(); - for(Account act_tmp: accounts) { - if(notify && act_tmp.getAcct().trim().equals(status.getAccount().getAcct()) && act_tmp.getId().trim().equals(status.getAccount().getId().trim())){ - notify = false; - } - } - //Here we check if the user wants home timeline notifications - if( notify ) - notify = sharedpreferences.getBoolean(Helper.SET_NOTIF_HOMETIMELINE, true); - } - lastPreviousContent = status.getContent(); - } - //All is good here for a notification, we will know check if it can be done depending of the hour - if( notify) - notify = canNotify(getApplicationContext()); - if( notify && event == EventStreaming.NOTIFICATION){ - intent = new Intent(getApplicationContext(), MainActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK ); - intent.putExtra(INTENT_ACTION, NOTIFICATION_INTENT); - intent.putExtra(PREF_KEY_ID, userId); - long notif_id = Long.parseLong(userId); - notificationId = ((notif_id + 1) > 2147483647) ? (int) (2147483647 - notif_id - 1) : (int) (notif_id + 1); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId, notification.getId()); - editor.apply(); - } - if( notify && event == EventStreaming.UPDATE) { - intent = new Intent(getApplicationContext(), MainActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); - intent.putExtra(INTENT_ACTION, HOME_TIMELINE_INTENT); - intent.putExtra(PREF_KEY_ID, userId); - long notif_id = Long.parseLong(userId); - notificationId = ((notif_id + 2) > 2147483647) ? (int) (2147483647 - notif_id - 2) : (int) (notif_id + 2); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, status.getId()); - editor.apply(); - } - - if( notify){ - if( notificationUrl != null){ - ImageLoader imageLoaderNoty = ImageLoader.getInstance(); - File cacheDir = new File(getApplicationContext().getCacheDir(), getString(R.string.app_name)); - ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) - .imageDownloader(new PatchBaseImageDownloader(getApplicationContext())) - .threadPoolSize(5) - .threadPriority(Thread.MIN_PRIORITY + 3) - .denyCacheImageMultipleSizesInMemory() - .diskCache(new UnlimitedDiskCache(cacheDir)) - .build(); - imageLoaderNoty.init(config); - DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) - .cacheOnDisk(true).resetViewBeforeLoading(true).build(); - - final String finalTitle = title; - imageLoaderNoty.loadImage(notificationUrl, options, new SimpleImageLoadingListener(){ - @Override - public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { - super.onLoadingComplete(imageUri, view, loadedImage); - notify_user(getApplicationContext(), intent, notificationId, loadedImage, finalTitle, message); - - } - @Override - public void onLoadingFailed(String imageUri, View view, FailReason failReason){ - notify_user(getApplicationContext(), intent, notificationId, BitmapFactory.decodeResource(getApplicationContext().getResources(), - R.drawable.mastodonlogo), finalTitle, message); - }}); - } - } - } - - private boolean isCurrentAccountLoggedIn(String acct, String userId){ - final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userconnected = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account account = new AccountDAO(getApplicationContext(), db).getAccountByID(userconnected); - return acct.trim().equals(account.getAcct().trim()) && userId.trim().equals(account.getId().trim()); + Intent intentBC = new Intent(Helper.RECEIVE_DATA); + intentBC.putExtra("eventStreaming", event); + LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBC); } } diff --git a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index c4126b554..ebc6a7d95 100644 --- a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -916,12 +916,18 @@ public class MainActivity extends AppCompatActivity StreamingService.StreamingServiceBinder binder = (StreamingService.StreamingServiceBinder) service; streamingService = binder.getService(); mBound = true; + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + SQLiteDatabase db = Sqlite.getInstance(MainActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + Account account = new AccountDAO(getApplicationContext(), db).getAccountByID(userId); + streamingService.connect(account); } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; + @Override protected void onStart() { super.onStart(); @@ -941,6 +947,8 @@ public class MainActivity extends AppCompatActivity protected void onPause() { super.onPause(); MainActivity.activityPaused(); + if( streamingService != null) + streamingService.disconnect(); } @Override From 9b8c6635e7adc70886b182fbd9e2ae9f7caa149e Mon Sep 17 00:00:00 2001 From: tom79 Date: Tue, 12 Sep 2017 19:18:55 +0200 Subject: [PATCH 3/8] Only connected account receives live events --- .../activities/MainActivity.java | 55 ++++++++++++---- app/src/main/AndroidManifest.xml | 7 +-- .../DisplayNotificationsFragment.java | 57 +---------------- .../fragments/DisplayStatusFragment.java | 63 +------------------ .../etalab/mastodon/services/BootService.java | 38 ----------- .../mastodon/services/StreamingService.java | 13 +++- .../layout-sw600dp/fragment_notifications.xml | 13 ---- .../res/layout-sw600dp/fragment_status.xml | 14 ----- .../res/layout/fragment_notifications.xml | 14 ----- app/src/main/res/layout/fragment_status.xml | 15 ----- .../activities/MainActivity.java | 30 ++++----- 11 files changed, 69 insertions(+), 250 deletions(-) delete mode 100644 app/src/main/java/fr/gouv/etalab/mastodon/services/BootService.java diff --git a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index dc8566632..fbc91a08d 100644 --- a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -16,10 +16,12 @@ package fr.gouv.etalab.mastodon.activities; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; +import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; +import android.content.ServiceConnection; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; @@ -27,6 +29,7 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; +import android.os.IBinder; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; @@ -38,7 +41,6 @@ import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.SearchView; import android.support.v7.widget.SwitchCompat; -import android.util.Log; import android.util.Patterns; import android.view.LayoutInflater; import android.view.View; @@ -146,19 +148,11 @@ public class MainActivity extends AppCompatActivity StreamingService.EventStreaming eventStreaming = (StreamingService.EventStreaming) intent.getSerializableExtra("eventStreaming"); if( eventStreaming == StreamingService.EventStreaming.NOTIFICATION){ if(notificationsFragment != null){ - if(notificationsFragment.getUserVisibleHint() && isActivityVisible()){ - notificationsFragment.showNewContent(); - }else{ - notificationsFragment.refresh(); - } + notificationsFragment.refresh(); } }else if(eventStreaming == StreamingService.EventStreaming.UPDATE){ if( homeFragment != null){ - if(homeFragment.getUserVisibleHint() && isActivityVisible()){ - homeFragment.showNewContent(); - }else{ - homeFragment.refresh(); - } + homeFragment.refresh(); } }else if(eventStreaming == StreamingService.EventStreaming.DELETE){ String id = b.getString("id"); @@ -174,6 +168,8 @@ public class MainActivity extends AppCompatActivity updateHomeCounter(); } }; + Intent intentService = new Intent(this, StreamingService.class); + bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE); LocalBroadcastManager.getInstance(this).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_DATA)); @@ -900,6 +896,37 @@ public class MainActivity extends AppCompatActivity new UpdateAccountInfoByIDAsyncTask(getApplicationContext(), MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } + + StreamingService streamingService = null; + boolean mBound = false; + private ServiceConnection serviceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName className, IBinder service) { + StreamingService.StreamingServiceBinder binder = (StreamingService.StreamingServiceBinder) service; + streamingService = binder.getService(); + mBound = true; + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + SQLiteDatabase db = Sqlite.getInstance(MainActivity.this, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + Account account = new AccountDAO(getApplicationContext(), db).getAccountByID(userId); + streamingService.connect(account); + } + @Override + public void onServiceDisconnected(ComponentName arg0) { + mBound = false; + } + }; + + @Override + protected void onStart() { + super.onStart(); + } + @Override + protected void onStop() { + super.onStop(); + + } + @Override protected void onPause() { super.onPause(); @@ -909,6 +936,12 @@ public class MainActivity extends AppCompatActivity @Override public void onDestroy(){ super.onDestroy(); + if( streamingService != null) + streamingService.disconnect(); + if (mBound) { + unbindService(serviceConnection); + mBound = false; + } LocalBroadcastManager.getInstance(this).unregisterReceiver(receive_data); } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f5475c694..355c1c189 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -24,7 +24,6 @@ - - - - - - + = 0 ; i--){ - notifications.add(0,notificationsTmp.get(i)); - } - boolean isOnWifi = Helper.isOnWIFI(context); - int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments, notifications); - lv_notifications.setAdapter(notificationsListAdapter); - if( notificationsTmp.size() > 0){ - SharedPreferences.Editor editor = sharedpreferences.edit(); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId, notificationsTmp.get(0).getId()); - editor.apply(); - } - if( notificationsTmp.size() > 0 && textviewNoAction.getVisibility() == View.VISIBLE) - textviewNoAction.setVisibility(View.GONE); - } - new_data.setVisibility(View.GONE); - notificationsTmp = new ArrayList<>(); - Helper.cacheNotificationsClear(context, null); - ((MainActivity) context).updateNotifCounter(); - } - }); return rootView; } @@ -190,27 +160,7 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve @Override public void onResume() { super.onResume(); - //New data are available - notificationsTmp = Helper.getTempNotification(context, null); - if (getUserVisibleHint() && notificationsTmp != null && notificationsTmp.size() > 0 && notifications.size() > 0) { - ArrayList added = new ArrayList<>(); - for(Notification notification : notifications){ - added.add(notification.getId()); - } - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - boolean isOnWifi = Helper.isOnWIFI(context); - int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - for(int i = notificationsTmp.size() -1 ; i >= 0 ; i--){ - if( !added.contains(notificationsTmp.get(i).getId())) { - this.notifications.add(0, notificationsTmp.get(i)); - added.add(notificationsTmp.get(i).getId()); - } - } - if( this.notifications.size() > 0 ) - max_id = this.notifications.get(this.notifications.size()-1).getId(); - notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments, notifications); - lv_notifications.setAdapter(notificationsListAdapter); - } + refresh(); } @Override @@ -288,10 +238,6 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } - public void showNewContent(){ - new_data.setVisibility(View.VISIBLE); - } - public void refresh(){ if( context == null) return; @@ -321,6 +267,5 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve if( textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } - new_data.setVisibility(View.GONE); } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index ffab4fe3d..17608c80b 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -32,7 +32,6 @@ import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import android.widget.RelativeLayout; -import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; @@ -76,7 +75,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private boolean isOnWifi; private int behaviorWithAttachments; private boolean showMediaOnly; - private TextView new_data; private int positionSpinnerTrans; private boolean hideHeader; private String instanceValue; @@ -128,7 +126,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn nextElementLoader.setVisibility(View.GONE); statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, this.statuses); lv_status.setAdapter(statusListAdapter); - new_data = (TextView) rootView.findViewById(R.id.new_data); if( !comesFromSearch){ //Hide account header when scrolling for ShowAccountActivity @@ -188,7 +185,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn firstLoad = true; flag_loading = true; swiped = true; - new_data.setVisibility(View.GONE); if( type == RetrieveFeedsAsyncTask.Type.USER) asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, showMediaOnly, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else if( type == RetrieveFeedsAsyncTask.Type.TAG) @@ -215,35 +211,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn textviewNoAction.setVisibility(View.VISIBLE); } - new_data.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - statusesTmp = Helper.getTempStatus(context, null); - if( statusesTmp != null){ - for(int i = statusesTmp.size() -1 ; i >= 0 ; i--){ - statuses.add(0,statusesTmp.get(i)); - } - boolean isOnWifi = Helper.isOnWIFI(context); - int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, statuses); - lv_status.setAdapter(statusListAdapter); - if( statusesTmp.size() > 0){ - SharedPreferences.Editor editor = sharedpreferences.edit(); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, statusesTmp.get(0).getId()); - editor.apply(); - } - if( statusesTmp.size() > 0 && textviewNoAction.getVisibility() == View.VISIBLE) - textviewNoAction.setVisibility(View.GONE); - } - new_data.setVisibility(View.GONE); - statusesTmp = new ArrayList<>(); - Helper.cacheStatusClear(context, null); - ((MainActivity) context).updateHomeCounter(); - - } - }); - return rootView; } @@ -259,30 +226,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override public void onResume() { super.onResume(); - if( type == RetrieveFeedsAsyncTask.Type.HOME ) { - //New data are available - statusesTmp = Helper.getTempStatus(context, null); - if (getUserVisibleHint() && statusesTmp != null && statusesTmp.size() > 0 && statuses.size() > 0) { - ArrayList added = new ArrayList<>(); - for (Status status : statuses) { - added.add(status.getId()); - } - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - boolean isOnWifi = Helper.isOnWIFI(context); - int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - int positionSpinnerTrans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); - for (int i = statusesTmp.size() - 1; i >= 0; i--) { - if (!added.contains(statusesTmp.get(i).getId())) { - this.statuses.add(0, statusesTmp.get(i)); - added.add(statusesTmp.get(i).getId()); - } - } - if (this.statuses.size() > 0) - max_id = this.statuses.get(this.statuses.size() - 1).getId(); - statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, statuses); - lv_status.setAdapter(statusListAdapter); - } - } + refresh(); } @Override @@ -372,10 +316,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } } - public void showNewContent(){ - new_data.setVisibility(View.VISIBLE); - } - @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); @@ -414,7 +354,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } - new_data.setVisibility(View.GONE); } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/services/BootService.java b/app/src/main/java/fr/gouv/etalab/mastodon/services/BootService.java deleted file mode 100644 index 147ef37a0..000000000 --- a/app/src/main/java/fr/gouv/etalab/mastodon/services/BootService.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.gouv.etalab.mastodon.services; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.database.sqlite.SQLiteDatabase; - -import java.util.List; - -import fr.gouv.etalab.mastodon.client.Entities.Account; -import fr.gouv.etalab.mastodon.sqlite.AccountDAO; -import fr.gouv.etalab.mastodon.sqlite.Sqlite; - -/** - * Created by Thomas on 29/08/2017. - * BroadcastReceiver to start service when device boot - */ - -public class BootService extends BroadcastReceiver { - - public BootService() { - } - - @Override - public void onReceive(Context context, Intent intent) { - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - List accounts = new AccountDAO(context, db).getAllAccount(); - if( accounts != null){ - for (Account account: accounts) { - Intent intentService = new Intent(context, StreamingService.class); - intentService.putExtra("acccountId", account.getId()); - intentService.putExtra("accountAcct", account.getAcct()); - context.startService(intentService); - } - } - } - -} \ No newline at end of file diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java index b41510665..61da454e9 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java @@ -24,6 +24,8 @@ import android.os.IBinder; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; +import android.util.Log; + import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; @@ -78,8 +80,14 @@ public class StreamingService extends Service { public void disconnect(){ - if( httpsURLConnection != null) - httpsURLConnection.disconnect(); + Thread readThread = new Thread(new Runnable() { + @Override + public void run() { + if( httpsURLConnection != null){ + httpsURLConnection.disconnect(); + } + }}); + readThread.start(); } @@ -165,6 +173,7 @@ public class StreamingService extends Service { break; } if (event !=null){ + if( (lastEvent == EventStreaming.NONE || lastEvent == null) && !event.startsWith("data: ")) { switch (event.trim()) { case "event: update": diff --git a/app/src/main/res/layout-sw600dp/fragment_notifications.xml b/app/src/main/res/layout-sw600dp/fragment_notifications.xml index 61dda0f44..690ab810f 100644 --- a/app/src/main/res/layout-sw600dp/fragment_notifications.xml +++ b/app/src/main/res/layout-sw600dp/fragment_notifications.xml @@ -80,18 +80,5 @@ android:indeterminate="true" /> - diff --git a/app/src/main/res/layout-sw600dp/fragment_status.xml b/app/src/main/res/layout-sw600dp/fragment_status.xml index 4f819e708..2b9b5bc3e 100644 --- a/app/src/main/res/layout-sw600dp/fragment_status.xml +++ b/app/src/main/res/layout-sw600dp/fragment_status.xml @@ -78,19 +78,5 @@ android:indeterminate="true" /> - - diff --git a/app/src/main/res/layout/fragment_notifications.xml b/app/src/main/res/layout/fragment_notifications.xml index 286913039..d1dd13d21 100644 --- a/app/src/main/res/layout/fragment_notifications.xml +++ b/app/src/main/res/layout/fragment_notifications.xml @@ -79,19 +79,5 @@ android:layout_height="match_parent" android:indeterminate="true" /> - - diff --git a/app/src/main/res/layout/fragment_status.xml b/app/src/main/res/layout/fragment_status.xml index 4d0ac9974..9810aa916 100644 --- a/app/src/main/res/layout/fragment_status.xml +++ b/app/src/main/res/layout/fragment_status.xml @@ -77,20 +77,5 @@ android:layout_height="match_parent" android:indeterminate="true" /> - - - diff --git a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index ebc6a7d95..3879dac08 100644 --- a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -30,7 +30,6 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.IBinder; -import android.os.Messenger; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; @@ -152,19 +151,11 @@ public class MainActivity extends AppCompatActivity StreamingService.EventStreaming eventStreaming = (StreamingService.EventStreaming) intent.getSerializableExtra("eventStreaming"); if( eventStreaming == StreamingService.EventStreaming.NOTIFICATION){ if(notificationsFragment != null){ - if(notificationsFragment.getUserVisibleHint() && isActivityVisible()){ - notificationsFragment.showNewContent(); - }else{ - notificationsFragment.refresh(); - } + notificationsFragment.refresh(); } }else if(eventStreaming == StreamingService.EventStreaming.UPDATE){ if( homeFragment != null){ - if(homeFragment.getUserVisibleHint() && isActivityVisible()){ - homeFragment.showNewContent(); - }else{ - homeFragment.refresh(); - } + homeFragment.refresh(); } }else if(eventStreaming == StreamingService.EventStreaming.DELETE){ String id = b.getString("id"); @@ -180,6 +171,8 @@ public class MainActivity extends AppCompatActivity updateHomeCounter(); } }; + Intent intentService = new Intent(this, StreamingService.class); + bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE); LocalBroadcastManager.getInstance(this).registerReceiver(receive_data, new IntentFilter(Helper.RECEIVE_DATA)); @@ -931,29 +924,28 @@ public class MainActivity extends AppCompatActivity @Override protected void onStart() { super.onStart(); - Intent intent = new Intent(this, StreamingService.class); - bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); - if (mBound) { - unbindService(serviceConnection); - mBound = false; - } + } @Override protected void onPause() { super.onPause(); MainActivity.activityPaused(); - if( streamingService != null) - streamingService.disconnect(); } @Override public void onDestroy(){ super.onDestroy(); + if( streamingService != null) + streamingService.disconnect(); + if (mBound) { + unbindService(serviceConnection); + mBound = false; + } LocalBroadcastManager.getInstance(this).unregisterReceiver(receive_data); } From 6ffce804e93e5a8d85077ebed4ab9fe7015bc7ed Mon Sep 17 00:00:00 2001 From: tom79 Date: Wed, 13 Sep 2017 08:38:08 +0200 Subject: [PATCH 4/8] New toots are sent directly to activity --- .../activities/MainActivity.java | 37 +++--- .../DisplayNotificationsFragment.java | 39 +----- .../fragments/DisplayStatusFragment.java | 50 +++----- .../gouv/etalab/mastodon/helper/Helper.java | 121 ------------------ .../mastodon/services/StreamingService.java | 13 +- 5 files changed, 50 insertions(+), 210 deletions(-) diff --git a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index fbc91a08d..198d06092 100644 --- a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -77,6 +77,8 @@ import java.util.regex.Matcher; import fr.gouv.etalab.mastodon.asynctasks.RetrieveMetaDataAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.UpdateAccountInfoByIDAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Account; +import fr.gouv.etalab.mastodon.client.Entities.Notification; +import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.fragments.DisplayAccountsFragment; import fr.gouv.etalab.mastodon.fragments.DisplayFollowRequestSentFragment; @@ -131,6 +133,8 @@ public class MainActivity extends AppCompatActivity private DisplayNotificationsFragment notificationsFragment; private BroadcastReceiver receive_data; private boolean display_local, display_global; + private int countNewStatus = 0; + private int countNewNotifications = 0; public MainActivity() { } @@ -148,11 +152,13 @@ public class MainActivity extends AppCompatActivity StreamingService.EventStreaming eventStreaming = (StreamingService.EventStreaming) intent.getSerializableExtra("eventStreaming"); if( eventStreaming == StreamingService.EventStreaming.NOTIFICATION){ if(notificationsFragment != null){ - notificationsFragment.refresh(); + Notification notification = b.getParcelable("data"); + notificationsFragment.refresh(notification); } }else if(eventStreaming == StreamingService.EventStreaming.UPDATE){ + Status status = b.getParcelable("data"); if( homeFragment != null){ - homeFragment.refresh(); + homeFragment.refresh(status); } }else if(eventStreaming == StreamingService.EventStreaming.DELETE){ String id = b.getString("id"); @@ -257,6 +263,12 @@ public class MainActivity extends AppCompatActivity tabLayout.addTab(tabPublic); viewPager = (ViewPager) findViewById(R.id.viewpager); + int countPage = 2; + if( sharedpreferences.getBoolean(Helper.SET_DISPLAY_LOCAL, true)) + countPage++; + if( sharedpreferences.getBoolean(Helper.SET_DISPLAY_GLOBAL, true)) + countPage++; + viewPager.setOffscreenPageLimit(countPage); main_app_container = (RelativeLayout) findViewById(R.id.main_app_container); PagerAdapter adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); @@ -283,21 +295,10 @@ public class MainActivity extends AppCompatActivity if( tab.getPosition() == 0) { item = navigationView.getMenu().findItem(R.id.nav_home); fragmentTag = "HOME_TIMELINE"; - if (homeFragment != null && Helper.getUnreadToots(getApplicationContext(), null) > 0) { - homeFragment.refresh(); - } - Helper.cacheStatusClear(getApplicationContext(), null); - updateHomeCounter(); }else if( tab.getPosition() == 1) { fragmentTag = "NOTIFICATIONS"; item = navigationView.getMenu().findItem(R.id.nav_notification); - if (notificationsFragment != null && Helper.getUnreadNotifications(getApplicationContext(), null) > 0) { - notificationsFragment.refresh(); - } - Helper.cacheNotificationsClear(getApplicationContext(), null); - updateNotifCounter(); }else if( tab.getPosition() == 2 && display_local) { - fragmentTag = "LOCAL_TIMELINE"; item = navigationView.getMenu().findItem(R.id.nav_local); }else if( tab.getPosition() == 2 && !display_local) { @@ -345,7 +346,7 @@ public class MainActivity extends AppCompatActivity DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment); if( displayStatusFragment != null ) displayStatusFragment.scrollToTop(); - Helper.cacheStatusClear(getApplicationContext(), null); + countNewStatus = 0; updateHomeCounter(); break; case 2: @@ -358,7 +359,7 @@ public class MainActivity extends AppCompatActivity DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment); if( displayNotificationsFragment != null ) displayNotificationsFragment.scrollToTop(); - Helper.cacheNotificationsClear(getApplicationContext(), null); + countNewNotifications = 0; updateNotifCounter(); break; } @@ -1157,8 +1158,7 @@ public class MainActivity extends AppCompatActivity if( tabHome == null) return; TextView tabCounterHome = (TextView) tabHome.findViewById(R.id.tab_counter); - tabCounterHome.setText(String.valueOf(Helper.getUnreadToots(getApplicationContext(), null))); - if( Helper.getUnreadToots(getApplicationContext(), null) > 0){ + if( countNewStatus> 0){ //New data are available //The fragment is not displayed, so the counter is displayed tabCounterHome.setVisibility(View.VISIBLE); @@ -1175,8 +1175,7 @@ public class MainActivity extends AppCompatActivity if( tabNotif == null) return; TextView tabCounterNotif = (TextView) tabNotif.findViewById(R.id.tab_counter); - tabCounterNotif.setText(String.valueOf(Helper.getUnreadNotifications(getApplicationContext(), null))); - if( Helper.getUnreadNotifications(getApplicationContext(), null) > 0){ + if( countNewNotifications > 0){ tabCounterNotif.setVisibility(View.VISIBLE); }else { tabCounterNotif.setVisibility(View.GONE); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java index 4ca4c4a54..bdcf20828 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java @@ -20,25 +20,18 @@ import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import android.widget.RelativeLayout; -import android.widget.TextView; import android.widget.Toast; - import java.util.ArrayList; import java.util.List; - -import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; -import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.drawers.NotificationsListAdapter; -import fr.gouv.etalab.mastodon.drawers.StatusListAdapter; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; import fr.gouv.etalab.mastodon.sqlite.Sqlite; @@ -61,7 +54,7 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve private AsyncTask asyncTask; private NotificationsListAdapter notificationsListAdapter; private String max_id; - private List notifications, notificationsTmp; + private List notifications; private RelativeLayout mainLoader, nextElementLoader, textviewNoAction; private boolean firstLoad; private SwipeRefreshLayout swipeRefreshLayout; @@ -160,14 +153,6 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve @Override public void onResume() { super.onResume(); - refresh(); - } - - @Override - public void setUserVisibleHint(boolean isVisibleToUser) { - super.setUserVisibleHint(isVisibleToUser); - if( isVisibleToUser ) - refresh(); } @Override @@ -195,8 +180,6 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve else textviewNoAction.setVisibility(View.GONE); if( swiped ){ - Helper.cacheNotificationsClear(context,null); - ((MainActivity) context).updateNotifCounter(); boolean isOnWifi = Helper.isOnWIFI(context); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments, this.notifications); @@ -238,29 +221,17 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } - public void refresh(){ + public void refresh(Notification notification){ if( context == null) return; - notificationsTmp = Helper.getTempNotification(context, null); - if( notificationsTmp.size() > 0){ - ArrayList added = new ArrayList<>(); - for(Notification notification : notifications){ - added.add(notification.getId()); - } - for(int i = notificationsTmp.size() -1 ; i >= 0 ; i--){ - if( !added.contains(notificationsTmp.get(i).getId())) { - this.notifications.add(0, notificationsTmp.get(i)); - added.add(notificationsTmp.get(i).getId()); - } - } - if( this.notifications.size() > 0 ) - max_id = this.notifications.get(this.notifications.size()-1).getId(); + if( notification != null){ + notifications.add(0, notification); boolean isOnWifi = Helper.isOnWIFI(context); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); SharedPreferences.Editor editor = sharedpreferences.edit(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId, notificationsTmp.get(0).getId()); + editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId, notification.getId()); editor.apply(); notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments, notifications); lv_notifications.setAdapter(notificationsListAdapter); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index 17608c80b..a9661ee52 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -25,7 +25,6 @@ import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -35,8 +34,6 @@ import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.List; - -import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRepliesAsyncTask; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; @@ -63,7 +60,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private AsyncTask asyncTask; private StatusListAdapter statusListAdapter; private String max_id; - private List statuses, statusesTmp; + private List statuses; private RetrieveFeedsAsyncTask.Type type; private RelativeLayout mainLoader, nextElementLoader, textviewNoAction; private boolean firstLoad; @@ -78,6 +75,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private int positionSpinnerTrans; private boolean hideHeader; private String instanceValue; + private String lastReadStatus; + private String userId; public DisplayStatusFragment(){ } @@ -117,7 +116,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn positionSpinnerTrans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer); behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - + userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + lastReadStatus = sharedpreferences.getString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, null); lv_status = (ListView) rootView.findViewById(R.id.lv_status); mainLoader = (RelativeLayout) rootView.findViewById(R.id.loader); nextElementLoader = (RelativeLayout) rootView.findViewById(R.id.loading_next_status); @@ -226,7 +226,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override public void onResume() { super.onResume(); - refresh(); } @Override @@ -269,14 +268,11 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn else textviewNoAction.setVisibility(View.GONE); if( swiped ){ - if( type == RetrieveFeedsAsyncTask.Type.HOME ) { - Helper.cacheStatusClear(context,null); - ((MainActivity) context).updateHomeCounter(); - } statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, this.statuses); lv_status.setAdapter(statusListAdapter); swiped = false; } + //Avoids to add a second time the same status, can happen due call in on resume ArrayList added = new ArrayList<>(); for(Status status : this.statuses){ added.add(status.getId()); @@ -286,6 +282,11 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if( !added.contains(tmpStatus.getId())) { this.statuses.add(tmpStatus); added.add(tmpStatus.getId()); + if( Long.parseLong(tmpStatus.getId()) > Long.parseLong(lastReadStatus)){ + tmpStatus.setNew(true); + }else { + tmpStatus.setNew(false); + } } } statusListAdapter.notifyDataSetChanged(); @@ -295,7 +296,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn //Store last toot id for home timeline to avoid to notify for those that have been already seen if(statuses != null && statuses.size() > 0 && type == RetrieveFeedsAsyncTask.Type.HOME ){ //acct is null when used in Fragment, data need to be retrieved via shared preferences and db - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account currentAccount = new AccountDAO(context, db).getAccountByID(userId); if( currentAccount != null && firstLoad && since_id != null){ @@ -316,38 +317,19 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } } - @Override - public void setUserVisibleHint(boolean isVisibleToUser) { - super.setUserVisibleHint(isVisibleToUser); - if( isVisibleToUser ) - refresh(); - } - - public void refresh(){ + public void refresh(Status status){ //New data are available if( type == RetrieveFeedsAsyncTask.Type.HOME ) { if (context == null) return; - statusesTmp = Helper.getTempStatus(context, null); - if (statusesTmp.size() > 0) { - ArrayList added = new ArrayList<>(); - for (Status status : statuses) { - added.add(status.getId()); - } - for (int i = statusesTmp.size() - 1; i >= 0; i--) { - if (!added.contains(statusesTmp.get(i).getId())) { - this.statuses.add(0, statusesTmp.get(i)); - added.add(statusesTmp.get(i).getId()); - } - } - if (this.statuses.size() > 0) - max_id = this.statuses.get(this.statuses.size() - 1).getId(); + if (status != null) { + statuses.add(0,status); boolean isOnWifi = Helper.isOnWIFI(context); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); SharedPreferences.Editor editor = sharedpreferences.edit(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, statusesTmp.get(0).getId()); + editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, status.getId()); editor.apply(); statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, statuses); lv_status.setAdapter(statusListAdapter); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index 1d9d64a5b..7c199aeb7 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -1597,125 +1597,4 @@ public class Helper { } } - - public static int getUnreadNotifications(Context context, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - Gson gson = new Gson(); - String json = sharedpreferences.getString(Helper.SET_TEMP_NOTIFICATIONS + userId, null); - Type type = new TypeToken>() {}.getType(); - ArrayList notifications = gson.fromJson(json, type); - return (notifications == null)?0:notifications.size(); - } - - - - public static int getUnreadToots(Context context, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - Gson gson = new Gson(); - String json = sharedpreferences.getString(Helper.SET_TEMP_STATUS + userId, null); - Type type = new TypeToken>() {}.getType(); - ArrayList statuses = gson.fromJson(json, type); - return (statuses == null)?0:statuses.size(); - } - - - public static void cacheStatus(Context context, Status status, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SharedPreferences.Editor editor = sharedpreferences.edit(); - ArrayList statuses = getTempStatus(context, userId); - if( statuses == null) - statuses = new ArrayList<>(); - if( status != null) - statuses.add(0,status); - Gson gson = new Gson(); - String serializedAccounts = gson.toJson(statuses); - editor.putString(Helper.SET_TEMP_STATUS + userId, serializedAccounts); - editor.apply(); - } - - public static void cacheStatusClear(Context context, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SharedPreferences.Editor editor = sharedpreferences.edit(); - ArrayList statuses = new ArrayList<>(); - Gson gson = new Gson(); - String serializedAccounts = gson.toJson(statuses); - editor.putString(Helper.SET_TEMP_STATUS + userId, serializedAccounts); - editor.apply(); - //noinspection EmptyTryBlock - try { - NotificationManager notificationManager = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); - long notif_id = Long.parseLong(userId); - int notificationId = ((notif_id + 2) > 2147483647) ? (int) (2147483647 - notif_id - 2) : (int) (notif_id + 2); - notificationManager.cancel(notificationId); - }catch (Exception ignored){} - } - - public static ArrayList getTempStatus(Context context, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - Gson gson = new Gson(); - String json = sharedpreferences.getString(Helper.SET_TEMP_STATUS + userId, null); - Type type = new TypeToken>() {}.getType(); - ArrayList statuses = gson.fromJson(json, type); - return (statuses != null)?statuses:new ArrayList(); - } - - - public static void cacheNotifications(Context context, Notification notification, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SharedPreferences.Editor editor = sharedpreferences.edit(); - ArrayList notifications = getTempNotification(context, userId); - if( notifications == null) - notifications = new ArrayList<>(); - if( notification != null) - notifications.add(0,notification); - Gson gson = new Gson(); - String serializedAccounts = gson.toJson(notifications); - editor.putString(Helper.SET_TEMP_NOTIFICATIONS + userId, serializedAccounts); - editor.apply(); - } - - public static void cacheNotificationsClear(Context context, String userId){ - - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SharedPreferences.Editor editor = sharedpreferences.edit(); - ArrayList notifications = new ArrayList<>(); - Gson gson = new Gson(); - String serializedAccounts = gson.toJson(notifications); - editor.putString(Helper.SET_TEMP_NOTIFICATIONS + userId, serializedAccounts); - editor.apply(); - //noinspection EmptyTryBlock - try { - NotificationManager notificationManager = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); - long notif_id = Long.parseLong(userId); - int notificationId = ((notif_id + 1) > 2147483647) ? (int) (2147483647 - notif_id - 1) : (int) (notif_id + 1); - notificationManager.cancel(notificationId); - }catch (Exception ignored){} - - } - - public static ArrayList getTempNotification(Context context, String userId){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - if( userId == null) - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - Gson gson = new Gson(); - String json = sharedpreferences.getString(Helper.SET_TEMP_NOTIFICATIONS + userId, null); - Type type = new TypeToken>() {}.getType(); - ArrayList notifications = gson.fromJson(json, type); - return (notifications != null)?notifications:new ArrayList(); - } - } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java index 61da454e9..fd11b9d4d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/services/StreamingService.java @@ -20,6 +20,7 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Binder; +import android.os.Bundle; import android.os.IBinder; import android.os.SystemClock; import android.support.annotation.Nullable; @@ -66,6 +67,11 @@ public class StreamingService extends Service { } private final IBinder iBinder = new StreamingServiceBinder(); + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + return START_STICKY; + } + public class StreamingServiceBinder extends Binder { public StreamingService getService() { return StreamingService.this; @@ -255,14 +261,16 @@ public class StreamingService extends Service { Status status ; Notification notification; String dataId = null; + + Bundle b = new Bundle(); if( event == EventStreaming.NOTIFICATION){ notification = API.parseNotificationResponse(getApplicationContext(), response); - Helper.cacheNotifications(getApplicationContext(), notification, userId); + b.putParcelable("data", notification); }else if ( event == EventStreaming.UPDATE){ status = API.parseStatuses(getApplicationContext(), response); status.setReplies(new ArrayList()); status.setNew(true); - Helper.cacheStatus(getApplicationContext(), status, userId); + b.putParcelable("data", status); }else if( event == EventStreaming.DELETE){ try { dataId = response.getString("id"); @@ -272,6 +280,7 @@ public class StreamingService extends Service { } Intent intentBC = new Intent(Helper.RECEIVE_DATA); intentBC.putExtra("eventStreaming", event); + intentBC.putExtras(b); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBC); } } From c1fd4b1d595b163135bcb6dd1698dd783300a43f Mon Sep 17 00:00:00 2001 From: tom79 Date: Wed, 13 Sep 2017 08:47:59 +0200 Subject: [PATCH 5/8] updates counters --- .../activities/MainActivity.java | 4 ++-- .../DisplayNotificationsFragment.java | 18 ++++++++------- .../fragments/DisplayStatusFragment.java | 22 ++++++++----------- 3 files changed, 21 insertions(+), 23 deletions(-) diff --git a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index 198d06092..e324217ba 100644 --- a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -133,8 +133,8 @@ public class MainActivity extends AppCompatActivity private DisplayNotificationsFragment notificationsFragment; private BroadcastReceiver receive_data; private boolean display_local, display_global; - private int countNewStatus = 0; - private int countNewNotifications = 0; + public static int countNewStatus = 0; + public static int countNewNotifications = 0; public MainActivity() { } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java index bdcf20828..fb39c26b3 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java @@ -29,6 +29,8 @@ import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.List; + +import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.drawers.NotificationsListAdapter; @@ -60,6 +62,8 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve private SwipeRefreshLayout swipeRefreshLayout; private boolean swiped; private ListView lv_notifications; + private String userId; + private String lastReadNotifications; public DisplayNotificationsFragment(){ } @@ -85,6 +89,8 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve nextElementLoader.setVisibility(View.GONE); boolean isOnWifi = Helper.isOnWIFI(context); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); + userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + lastReadNotifications = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId, null); notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments,this.notifications); lv_notifications.setAdapter(notificationsListAdapter); lv_notifications.setOnScrollListener(new AbsListView.OnScrollListener() { @@ -186,17 +192,13 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve lv_notifications.setAdapter(notificationsListAdapter); swiped = false; } - ArrayList added = new ArrayList<>(); - for(Notification notification : this.notifications){ - added.add(notification.getId()); - } if( notifications != null && notifications.size() > 0) { for(Notification tmpNotification: notifications){ - if( !added.contains(tmpNotification.getId())) { - this.notifications.add(tmpNotification); - added.add(tmpNotification.getId()); - } + if( Long.parseLong(tmpNotification.getId()) > Long.parseLong(lastReadNotifications)) + MainActivity.countNewNotifications++; + this.notifications.add(tmpNotification); } + ((MainActivity)context).updateNotifCounter(); notificationsListAdapter.notifyDataSetChanged(); } swipeRefreshLayout.setRefreshing(false); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index a9661ee52..66bb428b4 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -34,6 +34,8 @@ import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.List; + +import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRepliesAsyncTask; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; @@ -272,24 +274,18 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn lv_status.setAdapter(statusListAdapter); swiped = false; } - //Avoids to add a second time the same status, can happen due call in on resume - ArrayList added = new ArrayList<>(); - for(Status status : this.statuses){ - added.add(status.getId()); - } if( statuses != null && statuses.size() > 0) { for(Status tmpStatus: statuses){ - if( !added.contains(tmpStatus.getId())) { - this.statuses.add(tmpStatus); - added.add(tmpStatus.getId()); - if( Long.parseLong(tmpStatus.getId()) > Long.parseLong(lastReadStatus)){ - tmpStatus.setNew(true); - }else { - tmpStatus.setNew(false); - } + if( type == RetrieveFeedsAsyncTask.Type.HOME && firstLoad && Long.parseLong(tmpStatus.getId()) > Long.parseLong(lastReadStatus)){ + tmpStatus.setNew(true); + MainActivity.countNewStatus++; + }else { + tmpStatus.setNew(false); } + this.statuses.add(tmpStatus); } statusListAdapter.notifyDataSetChanged(); + ((MainActivity)context).updateHomeCounter(); } swipeRefreshLayout.setRefreshing(false); From c6305baa7c5aad1c1192835a8d57eab99c7d9f5f Mon Sep 17 00:00:00 2001 From: tom79 Date: Wed, 13 Sep 2017 15:21:03 +0200 Subject: [PATCH 6/8] Fixes some behaviors --- .../activities/MainActivity.java | 11 +++-- .../DisplayNotificationsFragment.java | 40 +++++++++--------- .../fragments/DisplayStatusFragment.java | 41 +++++++++---------- 3 files changed, 46 insertions(+), 46 deletions(-) diff --git a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index e324217ba..d0ba3d213 100644 --- a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -41,6 +41,7 @@ import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.SearchView; import android.support.v7.widget.SwitchCompat; +import android.util.Log; import android.util.Patterns; import android.view.LayoutInflater; import android.view.View; @@ -344,10 +345,10 @@ public class MainActivity extends AppCompatActivity switch (tab.getPosition()){ case 0: DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment); - if( displayStatusFragment != null ) - displayStatusFragment.scrollToTop(); countNewStatus = 0; updateHomeCounter(); + if( displayStatusFragment != null ) + displayStatusFragment.scrollToTop(); break; case 2: case 3: @@ -357,10 +358,10 @@ public class MainActivity extends AppCompatActivity break; case 1: DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment); - if( displayNotificationsFragment != null ) - displayNotificationsFragment.scrollToTop(); countNewNotifications = 0; updateNotifCounter(); + if( displayNotificationsFragment != null ) + displayNotificationsFragment.scrollToTop(); break; } } @@ -1158,6 +1159,7 @@ public class MainActivity extends AppCompatActivity if( tabHome == null) return; TextView tabCounterHome = (TextView) tabHome.findViewById(R.id.tab_counter); + tabCounterHome.setText(String.valueOf(countNewStatus)); if( countNewStatus> 0){ //New data are available //The fragment is not displayed, so the counter is displayed @@ -1175,6 +1177,7 @@ public class MainActivity extends AppCompatActivity if( tabNotif == null) return; TextView tabCounterNotif = (TextView) tabNotif.findViewById(R.id.tab_counter); + tabCounterNotif.setText(String.valueOf(countNewNotifications)); if( countNewNotifications > 0){ tabCounterNotif.setVisibility(View.VISIBLE); }else { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java index fb39c26b3..e36a118c4 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java @@ -20,6 +20,7 @@ import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -62,8 +63,8 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve private SwipeRefreshLayout swipeRefreshLayout; private boolean swiped; private ListView lv_notifications; - private String userId; private String lastReadNotifications; + private String userId; public DisplayNotificationsFragment(){ } @@ -175,10 +176,8 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve swiped = false; return; } - SharedPreferences.Editor editor = sharedpreferences.edit(); - List notifications = apiResponse.getNotifications(); - String since_id = apiResponse.getSince_id(); max_id = apiResponse.getMax_id(); + List notifications = apiResponse.getNotifications(); //The initial call comes from a classic tab refresh flag_loading = (max_id == null ); if( !swiped && firstLoad && (notifications == null || notifications.size() == 0)) @@ -192,30 +191,35 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve lv_notifications.setAdapter(notificationsListAdapter); swiped = false; } + if( firstLoad) + MainActivity.countNewNotifications = 0; if( notifications != null && notifications.size() > 0) { for(Notification tmpNotification: notifications){ if( Long.parseLong(tmpNotification.getId()) > Long.parseLong(lastReadNotifications)) MainActivity.countNewNotifications++; this.notifications.add(tmpNotification); } - ((MainActivity)context).updateNotifCounter(); notificationsListAdapter.notifyDataSetChanged(); } + if( firstLoad ) + ((MainActivity)context).updateNotifCounter(); swipeRefreshLayout.setRefreshing(false); - //Store last notification id to avoid to notify for those that have been already seen - if( notifications != null && notifications.size() > 0) { - //acct is null as userId when used in Fragment, data need to be retrieved via shared preferences and db - userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account currentAccount = new AccountDAO(context, db).getAccountByID(userId); - if( currentAccount != null && firstLoad && since_id != null){ - editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + currentAccount.getId(), notifications.get(0).getId()); - editor.apply(); - } - } firstLoad = false; } + @Override + public void setMenuVisibility(final boolean visible) { + super.setMenuVisibility(visible); + if( context == null) + return; + //Store last notification id to avoid to notify for those that have been already seen + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences.edit(); + if (visible && notifications != null && notifications.size() > 0) { + editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + this.userId, notifications.get(0).getId()); + editor.apply(); + } + } public void scrollToTop(){ if( lv_notifications != null) @@ -231,10 +235,6 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve boolean isOnWifi = Helper.isOnWIFI(context); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - SharedPreferences.Editor editor = sharedpreferences.edit(); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + userId, notification.getId()); - editor.apply(); notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments, notifications); lv_notifications.setAdapter(notificationsListAdapter); if( textviewNoAction.getVisibility() == View.VISIBLE) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index 66bb428b4..f97f53632 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -38,12 +38,9 @@ import java.util.List; import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRepliesAsyncTask; import fr.gouv.etalab.mastodon.client.APIResponse; -import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.drawers.StatusListAdapter; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRepliesInterface; -import fr.gouv.etalab.mastodon.sqlite.AccountDAO; -import fr.gouv.etalab.mastodon.sqlite.Sqlite; import mastodon.etalab.gouv.fr.mastodon.R; import fr.gouv.etalab.mastodon.asynctasks.RetrieveFeedsAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Status; @@ -261,7 +258,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn return; } List statuses = apiResponse.getStatuses(); - String since_id = apiResponse.getSince_id(); max_id = apiResponse.getMax_id(); flag_loading = (max_id == null ); @@ -274,6 +270,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn lv_status.setAdapter(statusListAdapter); swiped = false; } + if( firstLoad) + MainActivity.countNewStatus = 0; if( statuses != null && statuses.size() > 0) { for(Status tmpStatus: statuses){ if( type == RetrieveFeedsAsyncTask.Type.HOME && firstLoad && Long.parseLong(tmpStatus.getId()) > Long.parseLong(lastReadStatus)){ @@ -285,22 +283,10 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn this.statuses.add(tmpStatus); } statusListAdapter.notifyDataSetChanged(); + } + if( firstLoad) ((MainActivity)context).updateHomeCounter(); - } swipeRefreshLayout.setRefreshing(false); - - //Store last toot id for home timeline to avoid to notify for those that have been already seen - if(statuses != null && statuses.size() > 0 && type == RetrieveFeedsAsyncTask.Type.HOME ){ - //acct is null when used in Fragment, data need to be retrieved via shared preferences and db - - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account currentAccount = new AccountDAO(context, db).getAccountByID(userId); - if( currentAccount != null && firstLoad && since_id != null){ - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + currentAccount.getId(), statuses.get(0).getId()); - editor.apply(); - } - } firstLoad = false; //Retrieves replies @@ -323,10 +309,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn boolean isOnWifi = Helper.isOnWIFI(context); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - SharedPreferences.Editor editor = sharedpreferences.edit(); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, status.getId()); - editor.apply(); statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, statuses); lv_status.setAdapter(statusListAdapter); if (textviewNoAction.getVisibility() == View.VISIBLE) @@ -335,6 +317,21 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } } + @Override + public void setMenuVisibility(final boolean visible) { + super.setMenuVisibility(visible); + if( context == null) + return; + //Store last toot id for home timeline to avoid to notify for those that have been already seen + if (visible && statuses != null && statuses.size() > 0) { + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences.edit(); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, statuses.get(0).getId()); + editor.apply(); + } + } + public void scrollToTop(){ if( lv_status != null) lv_status.setAdapter(statusListAdapter); From 19da8d42f1322e18f89b2e21de66b9b19ac87030 Mon Sep 17 00:00:00 2001 From: tom79 Date: Wed, 13 Sep 2017 18:59:55 +0200 Subject: [PATCH 7/8] Fixes an issue with counters --- .../mastodon/fragments/DisplayNotificationsFragment.java | 4 ++-- .../etalab/mastodon/fragments/DisplayStatusFragment.java | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java index e36a118c4..c1735627d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java @@ -121,6 +121,7 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve firstLoad = true; flag_loading = true; swiped = true; + MainActivity.countNewNotifications = 0; asyncTask = new RetrieveNotificationsAsyncTask(context, null, null, max_id, null, null, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); @@ -191,8 +192,6 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve lv_notifications.setAdapter(notificationsListAdapter); swiped = false; } - if( firstLoad) - MainActivity.countNewNotifications = 0; if( notifications != null && notifications.size() > 0) { for(Notification tmpNotification: notifications){ if( Long.parseLong(tmpNotification.getId()) > Long.parseLong(lastReadNotifications)) @@ -218,6 +217,7 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve if (visible && notifications != null && notifications.size() > 0) { editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + this.userId, notifications.get(0).getId()); editor.apply(); + lastReadNotifications = notifications.get(0).getId(); } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index f97f53632..005aacf24 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -25,6 +25,7 @@ import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -184,6 +185,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn firstLoad = true; flag_loading = true; swiped = true; + MainActivity.countNewStatus = 0; if( type == RetrieveFeedsAsyncTask.Type.USER) asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, showMediaOnly, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else if( type == RetrieveFeedsAsyncTask.Type.TAG) @@ -270,8 +272,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn lv_status.setAdapter(statusListAdapter); swiped = false; } - if( firstLoad) - MainActivity.countNewStatus = 0; if( statuses != null && statuses.size() > 0) { for(Status tmpStatus: statuses){ if( type == RetrieveFeedsAsyncTask.Type.HOME && firstLoad && Long.parseLong(tmpStatus.getId()) > Long.parseLong(lastReadStatus)){ @@ -322,12 +322,14 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn super.setMenuVisibility(visible); if( context == null) return; + //Store last toot id for home timeline to avoid to notify for those that have been already seen - if (visible && statuses != null && statuses.size() > 0) { + if (type == RetrieveFeedsAsyncTask.Type.HOME && visible && statuses != null && statuses.size() > 0) { SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, statuses.get(0).getId()); + lastReadStatus = statuses.get(0).getId(); editor.apply(); } } From 8916803f470afa4e2796b115a78e41bc61d9d1c1 Mon Sep 17 00:00:00 2001 From: tom79 Date: Wed, 13 Sep 2017 19:09:35 +0200 Subject: [PATCH 8/8] Last fixes. --- .../activities/MainActivity.java | 3 +- .../activities/MainActivity.java | 45 ++++++++++--------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index d0ba3d213..942fa40c4 100644 --- a/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/fdroid/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -41,7 +41,6 @@ import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.SearchView; import android.support.v7.widget.SwitchCompat; -import android.util.Log; import android.util.Patterns; import android.view.LayoutInflater; import android.view.View; @@ -155,11 +154,13 @@ public class MainActivity extends AppCompatActivity if(notificationsFragment != null){ Notification notification = b.getParcelable("data"); notificationsFragment.refresh(notification); + countNewStatus++; } }else if(eventStreaming == StreamingService.EventStreaming.UPDATE){ Status status = b.getParcelable("data"); if( homeFragment != null){ homeFragment.refresh(status); + countNewNotifications++; } }else if(eventStreaming == StreamingService.EventStreaming.DELETE){ String id = b.getString("id"); diff --git a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java index 3879dac08..208c8895b 100644 --- a/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java +++ b/app/src/safetynet/java/fr.gouv.etalab.mastodon/activities/MainActivity.java @@ -79,6 +79,8 @@ import java.util.regex.Matcher; import fr.gouv.etalab.mastodon.asynctasks.RetrieveMetaDataAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.UpdateAccountInfoByIDAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Account; +import fr.gouv.etalab.mastodon.client.Entities.Notification; +import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.fragments.DisplayAccountsFragment; import fr.gouv.etalab.mastodon.fragments.DisplayFollowRequestSentFragment; @@ -134,6 +136,8 @@ public class MainActivity extends AppCompatActivity private static final int ERROR_DIALOG_REQUEST_CODE = 97; private BroadcastReceiver receive_data; private boolean display_local, display_global; + public static int countNewStatus = 0; + public static int countNewNotifications = 0; public MainActivity() { } @@ -151,11 +155,15 @@ public class MainActivity extends AppCompatActivity StreamingService.EventStreaming eventStreaming = (StreamingService.EventStreaming) intent.getSerializableExtra("eventStreaming"); if( eventStreaming == StreamingService.EventStreaming.NOTIFICATION){ if(notificationsFragment != null){ - notificationsFragment.refresh(); + Notification notification = b.getParcelable("data"); + notificationsFragment.refresh(notification); + countNewStatus++; } }else if(eventStreaming == StreamingService.EventStreaming.UPDATE){ + Status status = b.getParcelable("data"); if( homeFragment != null){ - homeFragment.refresh(); + homeFragment.refresh(status); + countNewNotifications++; } }else if(eventStreaming == StreamingService.EventStreaming.DELETE){ String id = b.getString("id"); @@ -261,6 +269,12 @@ public class MainActivity extends AppCompatActivity tabLayout.addTab(tabPublic); viewPager = (ViewPager) findViewById(R.id.viewpager); + int countPage = 2; + if( sharedpreferences.getBoolean(Helper.SET_DISPLAY_LOCAL, true)) + countPage++; + if( sharedpreferences.getBoolean(Helper.SET_DISPLAY_GLOBAL, true)) + countPage++; + viewPager.setOffscreenPageLimit(countPage); main_app_container = (RelativeLayout) findViewById(R.id.main_app_container); PagerAdapter adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); @@ -287,21 +301,10 @@ public class MainActivity extends AppCompatActivity if( tab.getPosition() == 0) { item = navigationView.getMenu().findItem(R.id.nav_home); fragmentTag = "HOME_TIMELINE"; - if (homeFragment != null && Helper.getUnreadToots(getApplicationContext(), null) > 0) { - homeFragment.refresh(); - } - Helper.cacheStatusClear(getApplicationContext(), null); - updateHomeCounter(); }else if( tab.getPosition() == 1) { fragmentTag = "NOTIFICATIONS"; item = navigationView.getMenu().findItem(R.id.nav_notification); - if (notificationsFragment != null && Helper.getUnreadNotifications(getApplicationContext(), null) > 0) { - notificationsFragment.refresh(); - } - Helper.cacheNotificationsClear(getApplicationContext(), null); - updateNotifCounter(); }else if( tab.getPosition() == 2 && display_local) { - fragmentTag = "LOCAL_TIMELINE"; item = navigationView.getMenu().findItem(R.id.nav_local); }else if( tab.getPosition() == 2 && !display_local) { @@ -347,10 +350,10 @@ public class MainActivity extends AppCompatActivity switch (tab.getPosition()){ case 0: DisplayStatusFragment displayStatusFragment = ((DisplayStatusFragment) fragment); + countNewStatus = 0; + updateHomeCounter(); if( displayStatusFragment != null ) displayStatusFragment.scrollToTop(); - Helper.cacheStatusClear(getApplicationContext(), null); - updateHomeCounter(); break; case 2: case 3: @@ -360,10 +363,10 @@ public class MainActivity extends AppCompatActivity break; case 1: DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment); + countNewNotifications = 0; + updateNotifCounter(); if( displayNotificationsFragment != null ) displayNotificationsFragment.scrollToTop(); - Helper.cacheNotificationsClear(getApplicationContext(), null); - updateNotifCounter(); break; } } @@ -1208,8 +1211,8 @@ public class MainActivity extends AppCompatActivity if( tabHome == null) return; TextView tabCounterHome = (TextView) tabHome.findViewById(R.id.tab_counter); - tabCounterHome.setText(String.valueOf(Helper.getUnreadToots(getApplicationContext(), null))); - if( Helper.getUnreadToots(getApplicationContext(), null) > 0){ + tabCounterHome.setText(String.valueOf(countNewStatus)); + if( countNewStatus> 0){ //New data are available //The fragment is not displayed, so the counter is displayed tabCounterHome.setVisibility(View.VISIBLE); @@ -1226,8 +1229,8 @@ public class MainActivity extends AppCompatActivity if( tabNotif == null) return; TextView tabCounterNotif = (TextView) tabNotif.findViewById(R.id.tab_counter); - tabCounterNotif.setText(String.valueOf(Helper.getUnreadNotifications(getApplicationContext(), null))); - if( Helper.getUnreadNotifications(getApplicationContext(), null) > 0){ + tabCounterNotif.setText(String.valueOf(countNewNotifications)); + if( countNewNotifications > 0){ tabCounterNotif.setVisibility(View.VISIBLE); }else { tabCounterNotif.setVisibility(View.GONE);