1
1

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.

AndroidでManagerClassにLifecycleのイベントを渡す

Posted at

こんにちは。m_saekiです。

ManagerClassとかでLifecycleのイベント渡したいときってありますよね?
そんな時はinterfaceで返せばOKです。

もっといい書き方はありそうなので、こうした方がいいよっていうのは是非ご教授お願いしますmm

1. LifecycleListener

LifecycleListener.interface
public interface LifeCycleListener {
    void create();
    void resume();
    void pause();
    void destory();
}

2. MainActivity

LifecycleListenerをセット

MainActivity.class
public class MainActivity extends AppCompatActivity {

	private LifeCycleListener lifeCycleListener;
	private Manager manager;

	@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        manager = new Manager(this);
        if (lifeCycleListener != null) lifeCycleListener.create();
        // ... proc
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (lifeCycleListener != null) lifeCycleListener.resume();
        // ... proc        
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (lifeCycleListener != null) lifeCycleListener.pause();
        // ... proc
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (lifeCycleListener != null) lifeCycleListener.destory();
        // ... proc        
    }
    
    public void setLifeCycleListener(@NonNull final LifeCycleListener lifeCycleListener) {
        this.lifeCycleListener = lifeCycleListener;
    }
}

3. Manager

Manager.class
public class Manager implements LifeCycleListener {

	public Manager(MainActivity activity) {
		activity.setLifeCycleListener(this);
	}

	@Override
    public void create() {
	    // ... proc
    }

    @Override
    public void resume() {
	    // ... proc    
    }

    @Override
    public void pause() {
	    // ... proc    
    }

    @Override
    public void destory() {
	    // ... proc    
    }
}

4. 終わりに

以上でManager.classにMaingActivityのLifecycleEventを受け取るように実装できます。
参考までに使ってもらえれば幸いです。

1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?