顯示具有 FixBugs 標籤的文章。 顯示所有文章
顯示具有 FixBugs 標籤的文章。 顯示所有文章

2017年12月5日 星期二

當Low memory時,Activity被銷毀了,但是Fragment重複產生

Reference:

http://juniperphoton.net/2017/03/27/jie-jue-viewpager-fragment-de-hui-fu-wen-ti/
http://y-anz-m.blogspot.tw/2013/07/viewpager-fragment.html
http://www.voidcn.com/article/p-weicgtjm-kv.html

Issue description:

當Low memory時,process被系統刪除,Activity被銷毀了,但是Fragment還在,導致Fragment重疊,造成開啟app的時間不斷增加

使用 adb shell dumpsys activity top 指令
可以發現 fragment數量不停累加

Solution:

在Activity被銷毀前,先將正在使用的fragment object儲存起來
下次開啟app後,再將前一次使用的fragment object (現在用不到的) 刪除掉

Code snippet:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Store the current used fragments
        if (mFragmentAdapter != null) {
            getSupportFragmentManager().putFragment(outState, KEY_FRAG_NAME1, mFragmentAdapter.getFragment(0));
            getSupportFragmentManager().putFragment(outState, KEY_FRAG_NAME2, mFragmentAdapter.getFragment(1));
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
.................
        // Remove previous unused fragments
        if (savedInstanceState != null) {
            mFragment1 = getSupportFragmentManager().getFragment(savedInstanceState,
                    KEY_FRAG_NAME1);
            mFragment2 = getSupportFragmentManager().getFragment(savedInstanceState,
                    KEY_FRAG_NAME2);

            if(mFragment1 != null || mFragment2 != null){
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.remove(mFragment1 );
                transaction.remove(mFragment2 );
                transaction.commit();
            }
        }
...............
    }

2017年11月22日 星期三

Notification icon flash on status bar

Problem:


當需要在短時間內持續更新notification的內容時
在建立Notification時,記得使用同一個Notification Builder物件,並且設定 setOnlyAlertOnce(true)
以免SystemUI一直在update notification,造成status bar UI一直在跳動

Code snippet:


return new Notification.Builder(context, NOTIFICATION_CHANNEL_ID)
            mBuilder
                        .setContentTitle(title)
                        .setContentText(contentText)
                        .setContentIntent(contentIntent)
                        .setSmallIcon(R.drawable.noti_icon)
                        .setLargeIcon(appIcon)
                        .setSubText(appLabel)
                        .setColor(color)
                        .setOnlyAlertOnce(true)
                        .addAction(stopAction)
                        //.addAction(optionsAction)

                        .build();