android jetpack LifeCycle的使用(java)

飞呀

  • 认识lifecycle
  • 使用LifeCycle
  • LifecycleService的使用
  • ProcessLifecycleOwner

认识lifecycle

用于系统组件的生命周期与普通组件之间的解耦。
具体表现为自定义组件不依赖页面(activity,fragment)生命周期的回调方法。
原理:通过对观察者模式,实现对页面生命周期的监听。观察者模式的两个类:LifecycleObserver和LifecycleOwner。
ComponentActivity实现了LifecycleOwner接口,通过LifecycleOwner的getLifecycle()方法来实现观察者模式。

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        ContextAware,
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner,
        ActivityResultRegistryOwner,
        ActivityResultCaller {

使用LifeCycle

自定义组件MyMediaPlayer,功能为进入页面自动播放音频文件,退到后台停止播放,清楚后台应用程序释放MediaPlayer。

public class MyMediaPlayer implements DefaultLifecycleObserver {


    private MediaPlayer mediaPlayer;


    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onCreate(owner);
        init();


        start("/storage/emulated/0/Android/data/cn.jn.mytest/files/a.mp3");

        Log.d("MyMediaPlayer", "onCreate");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onStop(owner);

        mediaPlayer.stop();
        Log.d("MyMediaPlayer", "onStop");
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onDestroy(owner);

        Log.d("MyMediaPlayer", "onDestroy");
        mediaPlayer.release();
    }

    private void init() {

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {

                mediaPlayer.start();
            }
        });
    }


    private void start(String url) {

        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

页面

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        getLifecycle().addObserver(new MyMediaPlayer());
    }

}

日志

---------------------------- PROCESS STARTED (20043) for package cn.jn.mytest ----------------------------
2023-04-08 15:14:59.915 20043-20043 MyMediaPlayer           cn.jn.mytest                         D  onCreate
2023-04-08 15:15:04.566 20043-20043 MyMediaPlayer           cn.jn.mytest                         D  onStop
2023-04-08 15:15:06.011 20043-20043 MyMediaPlayer           cn.jn.mytest                         D  onDestroy
---------------------------- PROCESS ENDED (20043) for package cn.jn.mytest ----------------------------

LifecycleService的使用

  1. 添加依赖
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
  1. 创建类,继承 LifecycleService类,声明MService 。
public class MService extends LifecycleService {
        <service
            android:name=".MService"
            android:exported="true" />
  1. 实现观察者 DefaultLifecycleObserver
    static class MyObserver implements DefaultLifecycleObserver {


        @Override
        public void onCreate(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onCreate(owner);

            Log.d("MService", "开启了服务");
        }

        @Override
        public void onDestroy(@NonNull LifecycleOwner owner) {
            DefaultLifecycleObserver.super.onDestroy(owner);

            Log.d("MService", "关闭了服务");
        }
    }
  1. 绑定观察者
    public MService() {

        MainActivity.MyObserver myObserver = new MainActivity.MyObserver();
        getLifecycle().addObserver(myObserver);
    }
  1. 查看效果
    开启服务
                Intent intent = new Intent(getApplicationContext(), MService.class);
                startService(intent);

关闭服务

                Intent intent = new Intent(getApplicationContext(), MService.class);
                stopService(intent);

日志

2023-04-08 16:32:44.552  7398-7398  MService                cn.jn.mytest                         D  开启了服务
2023-04-08 16:32:45.708  7398-7398  MService                cn.jn.mytest                         D  关闭了服务

ProcessLifecycleOwner

作用:监听这个应用的生命周期,可以判断当前应用是在前台还是在后台,或者从后台回到前台。

ProcessLifecycleOwner使用
ProcessLifecycleOwner要在Application中使用。onCreate的方法在整个应用生命周期中只会调用一次,onDestroy永远也不会调用。

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
              ProcessLifecycleOwner.get().getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onCreate(owner);

                Log.d("ProcessLifecycleOwner", "onCreate");
            }

            @Override
            public void onStart(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onStart(owner);

                isForeground = true;
                Log.d("ProcessLifecycleOwner", "onStart");
            }

            @Override
            public void onResume(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onResume(owner);

                Log.d("ProcessLifecycleOwner", "onResume");
            }

            @Override
            public void onPause(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onPause(owner);

                Log.d("ProcessLifecycleOwner", "onPause");
            }

            @Override
            public void onStop(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onStop(owner);

                isForeground = false;
                Log.d("ProcessLifecycleOwner", "onStop");
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);

                Log.d("ProcessLifecycleOwner", "onDestroy");
            }
        });

你可能感兴趣的:(java,android,jetpack,android)