1. 程式人生 > >模仿App後臺切換到前臺顯示閃屏(廣告)頁面

模仿App後臺切換到前臺顯示閃屏(廣告)頁面

感覺今年,後臺每一次切換到前臺,都顯示一次廣告頁面,這種實現的app越來越好,於是乎自己打算寫一個

1.感覺肯定是在生命週期的哪一個步驟之中觸發了這個功能,於是乎,寫了一遍生命週期,權當複習了,

public class AdvActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adv);
        Log.i("TAG"
,"onCreate"); } @Override protected void onStart() { super.onStart(); Log.i("TAG","onStart"); } @Override protected void onResume() { super.onResume(); Log.i("TAG","onResume"); } @Override protected void onPause() { super
.onPause(); Log.i("TAG","onPause"); } @Override protected void onStop() { super.onStop(); Log.i("TAG","onStop"); } @Override protected void onDestroy() { super.onDestroy(); Log.i("TAG","onDestroy"); } @Override protected void
onRestart() { super.onRestart(); Log.i("TAG","onRestart"); } }

於是乎,找到了,每次都出現的onresume 然後一想不對,這個每次都會出現,應該不合適,跳轉到廣告頁面,廣告頁面結束了,切回來的時候還是會觸發,onResume。
最終找到了onRestart ,測試了下
ok沒問題,目前完美實現需求
貼程式碼

/**
 * 廣告頁面模仿每次顯示出來廣告
 * @author fxr
 */
public class AdvActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adv);
        Log.i("TAG","onCreate");

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("TAG","onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("TAG","onResume");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("TAG","onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("TAG","onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("TAG","onDestroy");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i("TAG","onRestart");
        Intent intent=new Intent(AdvActivity.this,AdvTestActivity.class);
        startActivity(intent);
    }
}
public class AdvTestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adv_test);
        mHandler.sendEmptyMessageDelayed(0,3000);
    }
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            gohome();
            super.handleMessage(msg);
        }
    };

    private void gohome() {
        Intent intent=new Intent(AdvTestActivity.this,AdvActivity.class);
        startActivity(intent);
        finish();
    }
}