Android広告更新とフローティングボタンの自動非表示実装

Timerによる広告定期更新

Androidアプリケーションにおける広告管理では、Timerクラスを用いた定期更新が有効です。Timerはバックグラウンドスレッドでタスクをスケジュールし、広告コンテンツの自動更新を実現します。

// 広告更新用Timerの実装例
private Timer adUpdateTimer;

void startAdRefresh(long intervalMillis) {
    adUpdateTimer = new Timer(true);
    adUpdateTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            refreshAdContent();
        }
    }, 0, intervalMillis);
}

void refreshAdContent() {
    // 広告データ取得・UI更新処理
    runOnUiThread(() -> adView.loadNewAd());
}

void stopAdRefresh() {
    if (adUpdateTimer != null) {
        adUpdateTimer.cancel();
    }
}

注意点:

  • UI更新はrunOnUiThreadで実行
  • Activity終了時は必ずcancel()を呼び出し
  • ネットワークエラー時は再試行メカニズムを実装

FloatingActionButtonの基本設定

マテリアルデザインに準拠したFABの実装:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/actionButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_refresh"
    app:backgroundTint="@color/primary"
    app:layout_behavior=".CustomScrollBehavior" />

自動非表示機能の実装

CountDownTimer方式

private CountDownTimer autoHideTimer;

void showButtonTemporarily() {
    actionButton.show();
    startAutoHideTimer(3000);
}

void startAutoHideTimer(long delayMillis) {
    if (autoHideTimer != null) {
        autoHideTimer.cancel();
    }
    
    autoHideTimer = new CountDownTimer(delayMillis, 1000) {
        @Override
        public void onTick(long millisUntilDone) {}

        @Override
        public void onFinish() {
            actionButton.hide();
        }
    }.start();
}

Handler方式

private final Handler uiHandler = new Handler(Looper.getMainLooper());
private final Runnable hideAction = () -> actionButton.hide();

void showWithDelay() {
    actionButton.setVisibility(View.VISIBLE);
    uiHandler.removeCallbacks(hideAction);
    uiHandler.postDelayed(hideAction, 3000);
}

@Override
protected void onDestroy() {
    uiHandler.removeCallbacksAndMessages(null);
    super.onDestroy();
}

比較表:

方式メリット使用場面
CountDownTimer進捗コールバック可能カウント表示が必要な場合
Handler軽量で実装簡易シンプルな遅延処理

ライフサイクル管理

@Override
protected void onPause() {
    if (autoHideTimer != null) {
        autoHideTimer.cancel();
    }
    super.onPause();
}

@Override
protected void onResume() {
    if (shouldShowButton) {
        showButtonTemporarily();
    }
    super.onResume();
}

メモリリーク防止のため、コンポーネント破棄時にすべてのタイマーとハンドラーを解放することが不可欠です。

タグ: Android timer FloatingActionButton CountDownTimer Handler

7月15日 16:33 投稿