10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アプリ起動中に特定のActivityを開いているかどうか判定する

Last updated at Posted at 2017-02-16

アプリ起動中に特定のActivityでのみ処理を変更したいなどの場合に使えるtipsです。

対象のActivityでNAMEを定義

MyActivity.java

public class MyActivity extends AppCompatActivity {
    public static final String NAME = MyActivity.class.getName();
    
}

Application.ActivityLifecycleCallbacksの実装クラスを作成

MyLifecycleListener.java

public class MyLifecycleListener implements Application.ActivityLifecycleCallbacks {

    private static String currentActivityName = "";

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        //今回は表示されている画面を対象としたのでResumeで取得
        currentActivityName = activity.getClass().getName();
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    public static String getCurrentActivityName() {
        return currentActivityName;
    }
}

Applicationクラスで登録

MyApplication.java
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        registerActivityLifecycleCallbacks(new MyLifecycleListener());
    }
}

以上で設定は終了です。
あとは任意の場所で処理を行えます。

if (MyLifecycleListener.getCurrentActivityName().equals(MyActivity.NAME)) { 
    //do something.
}
10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?