├── car_hmi
├── .gitignore
├── libs
│ └── sdk.jar
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── themes.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── values-night
│ │ │ └── themes.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout
│ │ │ └── activity_hvac.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ └── com
│ │ │ └── mvvm
│ │ │ └── hmi
│ │ │ └── ipc
│ │ │ ├── model
│ │ │ ├── HvacCallback.java
│ │ │ └── HvacRepository.java
│ │ │ ├── CarApp.java
│ │ │ ├── ui
│ │ │ ├── HvacActivity.java
│ │ │ └── HvacViewModel.java
│ │ │ └── factory
│ │ │ ├── AppInjection.java
│ │ │ └── AppViewModelFactory.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── lib_mvvm_fwk
├── .gitignore
├── src
│ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── mvvm
│ │ │ └── fwk
│ │ │ ├── model
│ │ │ └── BaseRepository.java
│ │ │ ├── viewmodel
│ │ │ ├── BaseViewModel.java
│ │ │ └── BaseAndroidViewModel.java
│ │ │ ├── ui
│ │ │ ├── BaseBindingActivity.java
│ │ │ ├── BaseBindingFragment.java
│ │ │ ├── BaseActivity.java
│ │ │ ├── BaseMvvmActivity.java
│ │ │ ├── BaseMvvmFragment.java
│ │ │ └── BaseFragment.java
│ │ │ ├── utils
│ │ │ ├── eventbus
│ │ │ │ ├── LiveDataBus.java
│ │ │ │ └── StickyLiveData.java
│ │ │ ├── LogUtils.java
│ │ │ └── AppExecutors.java
│ │ │ └── AppGlobal.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── gradle.properties
├── gradlew.bat
├── gradlew
├── LICENSE
└── README.md
/car_hmi/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/lib_mvvm_fwk/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/car_hmi/libs/sdk.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/libs/sdk.jar
--------------------------------------------------------------------------------
/car_hmi/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | app_simple
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/model/BaseRepository.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.model;
2 |
3 | public abstract class BaseRepository {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | app
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/linxu-link/CarMvvmArch/HEAD/car_hmi/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/model/HvacCallback.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc.model;
2 |
3 | public interface HvacCallback {
4 |
5 | default void onTemperatureChanged(String temp){
6 |
7 | }
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Oct 30 20:59:15 CST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | dependencyResolutionManagement {
2 |
3 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
4 | repositories {
5 | google()
6 | mavenCentral()
7 | }
8 | }
9 | rootProject.name = "ARCH_MVVM"
10 | include ':lib_mvvm_fwk'
11 | //include ':app'
12 | include ':car_hmi'
13 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/CarApp.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc;
2 |
3 | import android.app.Application;
4 |
5 | public class CarApp extends Application {
6 |
7 | public static final String TAG_HVAC = "HVAC_";
8 |
9 | @Override
10 | public void onCreate() {
11 | super.onCreate();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/viewmodel/BaseViewModel.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.viewmodel;
2 |
3 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
4 |
5 | import androidx.lifecycle.ViewModel;
6 |
7 | import com.mvvm.fwk.model.BaseRepository;
8 | import com.mvvm.fwk.utils.LogUtils;
9 |
10 | public abstract class BaseViewModel extends ViewModel {
11 |
12 | private final String TAG = TAG_FWK + getClass().getSimpleName();
13 |
14 | protected M mRepository;
15 |
16 | public BaseViewModel(M repository) {
17 | mRepository = repository;
18 | }
19 |
20 | public M getRepository() {
21 | return mRepository;
22 | }
23 |
24 | @Override
25 | protected void onCleared() {
26 | super.onCleared();
27 | LogUtils.logV(TAG, "[onCleared]");
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/car_hmi/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/lib_mvvm_fwk/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/car_hmi/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/car_hmi/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
14 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/viewmodel/BaseAndroidViewModel.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.viewmodel;
2 |
3 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
4 |
5 | import android.app.Application;
6 |
7 | import androidx.annotation.Nullable;
8 | import androidx.lifecycle.AndroidViewModel;
9 |
10 | import com.mvvm.fwk.model.BaseRepository;
11 | import com.mvvm.fwk.utils.LogUtils;
12 |
13 | public abstract class BaseAndroidViewModel extends AndroidViewModel {
14 |
15 | private final String TAG = TAG_FWK + getClass().getSimpleName();
16 |
17 | protected M mRepository;
18 |
19 | public BaseAndroidViewModel(Application application, @Nullable M repository) {
20 | super(application);
21 | mRepository = repository;
22 | }
23 |
24 | public M getRepository() {
25 | return mRepository;
26 | }
27 |
28 | @Override
29 | protected void onCleared() {
30 | super.onCleared();
31 | LogUtils.logV(TAG, "[onCleared]");
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/ui/BaseBindingActivity.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.ui;
2 |
3 | import android.os.Bundle;
4 |
5 | import androidx.annotation.LayoutRes;
6 | import androidx.annotation.Nullable;
7 | import androidx.databinding.DataBindingUtil;
8 | import androidx.databinding.ViewDataBinding;
9 |
10 | public abstract class BaseBindingActivity extends BaseActivity {
11 |
12 | protected V mBinding;
13 |
14 | @Override
15 | protected void onCreate(@Nullable Bundle savedInstanceState) {
16 | super.onCreate(savedInstanceState);
17 | if (getLayoutId() == 0) {
18 | throw new RuntimeException("getLayout() must be not null");
19 | }
20 | mBinding = DataBindingUtil.setContentView(this, getLayoutId());
21 | mBinding.setLifecycleOwner(this);
22 | mBinding.executePendingBindings();
23 | initView();
24 | }
25 |
26 | @LayoutRes
27 | protected abstract int getLayoutId();
28 |
29 | public V getBinding() {
30 | return mBinding;
31 | }
32 |
33 | protected abstract void initView();
34 | }
35 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/ui/HvacActivity.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc.ui;
2 |
3 | import android.content.Intent;
4 |
5 | import androidx.lifecycle.Observer;
6 |
7 | import com.mvvm.fwk.ui.BaseMvvmActivity;
8 | import com.mvvm.fwk.utils.LogUtils;
9 | import com.mvvm.fwk.utils.eventbus.LiveDataBus;
10 | import com.mvvm.hmi.ipc.BR;
11 | import com.mvvm.hmi.ipc.CarApp;
12 | import com.mvvm.hmi.ipc.R;
13 | import com.mvvm.hmi.ipc.databinding.ActivityHvacBinding;
14 | import com.mvvm.hmi.ipc.factory.AppInjection;
15 |
16 | public class HvacActivity extends BaseMvvmActivity{
17 |
18 | @Override
19 | protected int getLayoutId() {
20 | return R.layout.activity_hvac;
21 | }
22 |
23 | @Override
24 | protected void initView() {
25 |
26 | }
27 |
28 | @Override
29 | protected Object getViewModelOrFactory() {
30 | return AppInjection.getViewModelFactory();
31 | }
32 |
33 | @Override
34 | protected int getViewModelVariable() {
35 | return 0;
36 | }
37 |
38 | @Override
39 | protected void initObservable(HvacViewModel viewModel) {
40 |
41 | }
42 |
43 | @Override
44 | protected void loadData(HvacViewModel viewModel) {
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/factory/AppInjection.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc.factory;
2 |
3 | import androidx.lifecycle.ViewModel;
4 | import androidx.lifecycle.ViewModelProvider;
5 | import androidx.lifecycle.ViewModelStoreOwner;
6 |
7 | import com.fwk.sdk.hvac.HvacManager;
8 | import com.mvvm.hmi.ipc.model.HvacRepository;
9 |
10 | /**
11 | * 统一生成APP中 ViewModel & Repository.
12 | * 统一管理APP中的所有单例类.
13 | *
14 | * @author WuJia
15 | * @version 1.0
16 | * @date 2021/11/14
17 | */
18 | public class AppInjection {
19 |
20 | // ViewModel 工厂
21 | private final static AppViewModelFactory mViewModelFactory = new AppViewModelFactory();
22 |
23 | public static T getViewModel(ViewModelStoreOwner store, Class clazz) {
24 | return new ViewModelProvider(store, mViewModelFactory).get(clazz);
25 | }
26 |
27 | public static AppViewModelFactory getViewModelFactory() {
28 | return mViewModelFactory;
29 | }
30 |
31 | /**
32 | * 受保护的权限,除了ViewModel,其它模块不应该需要Model层的实例
33 | *
34 | * @return {@link HvacRepository}
35 | */
36 | protected static HvacRepository getHvacRepository() {
37 | return new HvacRepository(getHvacManager());
38 | }
39 |
40 | public static HvacManager getHvacManager() {
41 | return HvacManager.getInstance();
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/factory/AppViewModelFactory.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc.factory;
2 |
3 | import androidx.annotation.NonNull;
4 | import androidx.lifecycle.ViewModel;
5 | import androidx.lifecycle.ViewModelProvider;
6 |
7 | import com.mvvm.fwk.utils.AppExecutors;
8 | import com.mvvm.hmi.ipc.model.HvacRepository;
9 | import com.mvvm.hmi.ipc.ui.HvacViewModel;
10 |
11 | import java.lang.reflect.InvocationTargetException;
12 |
13 | // default 权限,不对外部公开此类
14 | class AppViewModelFactory implements ViewModelProvider.Factory {
15 |
16 | // 创建 viewModel 实例
17 | @NonNull
18 | @Override
19 | public T create(@NonNull Class modelClass) {
20 | try {
21 | if (modelClass == HvacViewModel.class) {
22 | return modelClass.getConstructor(HvacRepository.class, AppExecutors.class)
23 | .newInstance(AppInjection.getHvacRepository(), AppExecutors.get());
24 | } else {
25 | throw new RuntimeException(modelClass.getSimpleName() + "create failed");
26 | }
27 | } catch (NoSuchMethodException | IllegalAccessException
28 | | InstantiationException | InvocationTargetException exception) {
29 | exception.printStackTrace();
30 | throw new RuntimeException(exception);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | }
4 |
5 | android {
6 | compileSdk 31
7 |
8 | defaultConfig {
9 | minSdk 21
10 | targetSdk 31
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 |
15 | compileOptions {
16 | sourceCompatibility JavaVersion.VERSION_1_8
17 | targetCompatibility JavaVersion.VERSION_1_8
18 | }
19 |
20 | buildFeatures {
21 | dataBinding true
22 | }
23 | }
24 |
25 | dependencies {
26 | compileOnly 'androidx.appcompat:appcompat:1.2.0'
27 | compileOnly 'com.google.android.material:material:1.3.0'
28 | }
29 |
30 | //makeJar
31 | def zipFile = file('build/intermediates/aar_main_jar/release/classes.jar')
32 | task makeJar(type: Jar) {
33 | from zipTree(zipFile)
34 | archiveBaseName = "fwk_mvvm"
35 | destinationDirectory = file("build/outputs/")
36 | manifest {
37 | attributes(
38 | 'Implementation-Title': "${project.name}",
39 | 'Built-Date': new Date().getDateTimeString(),
40 | 'Built-With':
41 | "gradle-${project.getGradle().getGradleVersion()},groovy-${GroovySystem.getVersion()}",
42 | 'Created-By':
43 | 'Java ' + System.getProperty('java.version') + ' (' + System.getProperty('java.vendor') + ')')
44 | }
45 | }
46 | makeJar.dependsOn(build)
--------------------------------------------------------------------------------
/car_hmi/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | }
4 |
5 | android {
6 | compileSdk 31
7 |
8 | defaultConfig {
9 | applicationId "com.mvvm.hmi.ipc"
10 | minSdk 21
11 | targetSdk 31
12 | versionCode 1
13 | versionName "1.0"
14 |
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 | compileOptions {
25 | sourceCompatibility JavaVersion.VERSION_1_8
26 | targetCompatibility JavaVersion.VERSION_1_8
27 | }
28 | buildFeatures {
29 | dataBinding true
30 | }
31 | }
32 |
33 | dependencies {
34 | implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
35 | implementation "androidx.lifecycle:lifecycle-livedata:2.3.0"
36 | implementation "androidx.lifecycle:lifecycle-viewmodel:2.3.0"
37 | implementation 'androidx.appcompat:appcompat:1.2.0'
38 | implementation 'com.google.android.material:material:1.3.0'
39 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
40 | implementation "com.google.code.gson:gson:2.8.6"
41 | implementation 'com.squareup.retrofit2:retrofit:2.9.0'
42 | implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
43 | implementation'com.squareup.okhttp3:logging-interceptor:3.4.1'
44 | implementation project(":lib_mvvm_fwk")
45 | }
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/ui/BaseBindingFragment.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.ui;
2 |
3 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
4 |
5 | import android.os.Bundle;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 |
10 | import androidx.annotation.LayoutRes;
11 | import androidx.annotation.NonNull;
12 | import androidx.annotation.Nullable;
13 | import androidx.databinding.DataBindingUtil;
14 | import androidx.databinding.ViewDataBinding;
15 |
16 | import com.mvvm.fwk.utils.LogUtils;
17 |
18 | public abstract class BaseBindingFragment extends BaseFragment {
19 |
20 | private static final String TAG = TAG_FWK + BaseBindingFragment.class.getSimpleName();
21 |
22 | protected V mBinding;
23 |
24 | @Nullable
25 | @Override
26 | public View onCreateView(@NonNull LayoutInflater inflater,
27 | @Nullable ViewGroup container,
28 | @Nullable Bundle savedInstanceState) {
29 | LogUtils.logV(TAG, "[onCreateView]");
30 | if (getLayoutId() == 0) {
31 | throw new RuntimeException("getLayout() must be not null");
32 | }
33 | mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
34 | mBinding.setLifecycleOwner(this);
35 | mBinding.executePendingBindings();
36 | initView();
37 | return mBinding.getRoot();
38 | }
39 |
40 | protected abstract void initView();
41 |
42 | @LayoutRes
43 | protected abstract int getLayoutId();
44 |
45 | public V getBinding() {
46 | return mBinding;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/layout/activity_hvac.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
11 |
12 |
13 |
16 |
17 |
28 |
29 |
38 |
39 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/utils/eventbus/LiveDataBus.java:
--------------------------------------------------------------------------------
1 | //
2 | // CONFIDENTIAL - FORD MOTOR COMPANY
3 | //
4 | // This is an unpublished work, which is a trade secret, created in
5 | // 2021. Ford Motor Company owns all rights to this work and intends
6 | // to maintain it in confidence to preserve its trade secret status.
7 | // Ford Motor Company reserves the right to protect this work as an
8 | // unpublished copyrighted work in the event of an inadvertent or
9 | // deliberate unauthorized publication. Ford Motor Company also
10 | // reserves its rights under the copyright laws to protect this work
11 | // as a published work. Those having access to this work may not copy
12 | // it, use it, or disclose the information contained in it without
13 | // the written authorization of Ford Motor Company.
14 | //
15 |
16 | package com.mvvm.fwk.utils.eventbus;
17 |
18 | import java.util.concurrent.ConcurrentHashMap;
19 |
20 | /**
21 | * Event bus achieved by LiveData.
22 | *
23 | * @author WuJia.
24 | * @version 1.0
25 | * @date 2020/10/31
26 | */
27 | public class LiveDataBus {
28 |
29 | private static class Lazy {
30 | static LiveDataBus sLiveDataBus = new LiveDataBus();
31 | }
32 |
33 | public static LiveDataBus getInstance() {
34 | return Lazy.sLiveDataBus;
35 | }
36 |
37 | private final ConcurrentHashMap mHashMap = new ConcurrentHashMap<>();
38 |
39 | /**
40 | * Input event name.
41 | *
42 | * @param channelName event name
43 | * @return see {@link StickyLiveData}
44 | */
45 | public StickyLiveData getChannel(String channelName) {
46 | StickyLiveData liveData = mHashMap.get(channelName);
47 | if (liveData == null) {
48 | liveData = new StickyLiveData(channelName);
49 | liveData.setDestroyListener(new StickyLiveData.IDestroyListener() {
50 | @Override
51 | public void onLiveDataDestroy(String channelName) {
52 | mHashMap.remove(channelName);
53 | }
54 | });
55 | mHashMap.put(channelName, liveData);
56 | }
57 | return liveData;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/model/HvacRepository.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc.model;
2 |
3 | import android.text.TextUtils;
4 |
5 | import com.fwk.sdk.hvac.HvacManager;
6 | import com.fwk.sdk.hvac.IHvacCallback;
7 | import com.mvvm.fwk.model.BaseRepository;
8 | import com.mvvm.fwk.utils.LogUtils;
9 | import com.mvvm.hmi.ipc.CarApp;
10 |
11 | public class HvacRepository extends BaseRepository {
12 |
13 | private static final String TAG = CarApp.TAG_HVAC + HvacRepository.class.getSimpleName();
14 |
15 | private final HvacManager mHvacManager;
16 | private HvacCallback mHvacViewModelCallback;
17 |
18 | private final IHvacCallback mHvacCallback = new IHvacCallback() {
19 | @Override
20 | public void onTemperatureChanged(double temp) {
21 | if (mHvacViewModelCallback != null) {
22 | // 处理远程数据,将它转换为应用中需要的数据格式或内容
23 | String value = String.valueOf(temp);
24 | mHvacViewModelCallback.onTemperatureChanged(value);
25 | }
26 | }
27 | };
28 |
29 | public HvacRepository(HvacManager hvacManager) {
30 | mHvacManager = hvacManager;
31 | mHvacManager.registerCallback(mHvacCallback);
32 | }
33 |
34 | public void release() {
35 | mHvacManager.unregisterCallback(mHvacCallback);
36 | }
37 |
38 | public void requestTemperature() {
39 | LogUtils.logI(TAG, "[requestTemperature]");
40 | HvacManager.getInstance().requestTemperature();
41 | }
42 |
43 | public void setTemperature(String temperature) {
44 | LogUtils.logI(TAG, "[setTemperature] " + temperature);
45 | if (temperature == null || TextUtils.isEmpty(temperature)) {
46 | return;
47 | }
48 | mHvacManager.setTemperature(Integer.parseInt(temperature));
49 | }
50 |
51 | public void setHvacListener(HvacCallback callback) {
52 | LogUtils.logI(TAG, "[setHvacListener] " + callback);
53 | mHvacViewModelCallback = callback;
54 | }
55 |
56 | public void removeHvacListener(HvacCallback callback) {
57 | LogUtils.logI(TAG, "[removeHvacListener] " + callback);
58 | mHvacViewModelCallback = null;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/car_hmi/src/main/java/com/mvvm/hmi/ipc/ui/HvacViewModel.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.hmi.ipc.ui;
2 |
3 | import android.view.View;
4 |
5 | import androidx.lifecycle.LiveData;
6 | import androidx.lifecycle.MutableLiveData;
7 |
8 | import com.mvvm.fwk.utils.AppExecutors;
9 | import com.mvvm.fwk.utils.LogUtils;
10 | import com.mvvm.fwk.utils.eventbus.LiveDataBus;
11 | import com.mvvm.fwk.viewmodel.BaseViewModel;
12 | import com.mvvm.hmi.ipc.CarApp;
13 | import com.mvvm.hmi.ipc.model.HvacCallback;
14 | import com.mvvm.hmi.ipc.model.HvacRepository;
15 |
16 | public class HvacViewModel extends BaseViewModel {
17 |
18 | private static final String TAG = CarApp.TAG_HVAC + HvacViewModel.class.getSimpleName();
19 |
20 | private final HvacRepository mRepository;
21 | // 线程池框架。某些场景,ViewModel访问Repository中的方法可能会需要切换到子线程。
22 | private final AppExecutors mAppExecutors;
23 | private MutableLiveData mTempLive;
24 |
25 | private final HvacCallback mHvacCallback = new HvacCallback() {
26 | @Override
27 | public void onTemperatureChanged(String temp) {
28 | LogUtils.logI(TAG, "[onTemperatureChanged] " + temp);
29 | getTempLive().postValue(temp);
30 | }
31 | };
32 |
33 | public HvacViewModel(HvacRepository repository, AppExecutors executors) {
34 | super(repository);
35 | mRepository = repository;
36 | mAppExecutors = executors;
37 | mRepository.setHvacListener(mHvacCallback);
38 | }
39 |
40 | @Override
41 | protected void onCleared() {
42 | super.onCleared();
43 | mRepository.removeHvacListener(mHvacCallback);
44 | mRepository.release();
45 | }
46 |
47 | /**
48 | * 请求页面数据
49 | */
50 | public void requestTemperature() {
51 | mRepository.requestTemperature();
52 | }
53 |
54 | /**
55 | * 将温度数据设定到Service中
56 | *
57 | * @param view
58 | */
59 | public void setTemperature(View view) {
60 | mRepository.setTemperature(getTempLive().getValue());
61 | }
62 |
63 | public MutableLiveData getTempLive() {
64 | if (mTempLive == null) {
65 | mTempLive = new MutableLiveData<>();
66 | }
67 | return mTempLive;
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/ui/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.ui;
2 |
3 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
4 |
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 |
8 | import androidx.annotation.NonNull;
9 | import androidx.annotation.Nullable;
10 | import androidx.appcompat.app.AppCompatActivity;
11 |
12 | import com.mvvm.fwk.utils.LogUtils;
13 |
14 | public abstract class BaseActivity extends AppCompatActivity {
15 |
16 | private final String TAG = TAG_FWK + getClass().getSimpleName();
17 |
18 | @Override
19 | protected void onCreate(@Nullable Bundle savedInstanceState) {
20 | super.onCreate(savedInstanceState);
21 | LogUtils.logV(TAG, "[onCreate]");
22 | }
23 |
24 | @Override
25 | protected void onStart() {
26 | super.onStart();
27 | LogUtils.logV(TAG, "[onStart]");
28 | }
29 |
30 | @Override
31 | protected void onRestart() {
32 | super.onRestart();
33 | LogUtils.logV(TAG, "[onRestart]");
34 | }
35 |
36 | @Override
37 | protected void onSaveInstanceState(@NonNull Bundle outState) {
38 | super.onSaveInstanceState(outState);
39 | LogUtils.logV(TAG, "[onSaveInstanceState]");
40 | }
41 |
42 | @Override
43 | protected void onNewIntent(Intent intent) {
44 | super.onNewIntent(intent);
45 | if (intent != null) {
46 | LogUtils.logV(TAG, "[onNewIntent]" + intent.toString());
47 | }
48 | }
49 |
50 | @Override
51 | protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
52 | super.onActivityResult(requestCode, resultCode, data);
53 | LogUtils.logV(TAG, "[onActivityResult] requestCode:" + requestCode + ";"
54 | + "resultCode:" + requestCode);
55 | }
56 |
57 | @Override
58 | protected void onResume() {
59 | super.onResume();
60 | LogUtils.logV(TAG, "[onResume]");
61 | }
62 |
63 | @Override
64 | public void onPause() {
65 | super.onPause();
66 | LogUtils.logV(TAG, "[onPause]");
67 | }
68 |
69 | @Override
70 | protected void onStop() {
71 | super.onStop();
72 | LogUtils.logV(TAG, "[onStop]");
73 | }
74 |
75 | @Override
76 | protected void onDestroy() {
77 | super.onDestroy();
78 | LogUtils.logV(TAG, "[onDestroy]");
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/ui/BaseMvvmActivity.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.ui;
2 |
3 | import android.os.Bundle;
4 |
5 | import androidx.annotation.Nullable;
6 | import androidx.databinding.ViewDataBinding;
7 | import androidx.lifecycle.ViewModel;
8 | import androidx.lifecycle.ViewModelProvider;
9 | import androidx.lifecycle.ViewModelStoreOwner;
10 |
11 | import com.mvvm.fwk.viewmodel.BaseViewModel;
12 |
13 | import java.lang.reflect.ParameterizedType;
14 | import java.lang.reflect.Type;
15 |
16 | public abstract class BaseMvvmActivity extends BaseBindingActivity {
17 |
18 | protected Vm mViewModel;
19 |
20 | @Override
21 | protected void onCreate(@Nullable Bundle savedInstanceState) {
22 | initViewModel();
23 | super.onCreate(savedInstanceState);
24 | if (getViewModelVariable() != 0) {
25 | mBinding.setVariable(getViewModelVariable(), mViewModel);
26 | }
27 | mBinding.executePendingBindings();
28 | initObservable(mViewModel);
29 | }
30 |
31 | @Override
32 | protected void onStart() {
33 | super.onStart();
34 | loadData(mViewModel);
35 | }
36 |
37 | private void initViewModel() {
38 | Class modelClass;
39 | Type type = getClass().getGenericSuperclass();
40 | if (type instanceof ParameterizedType) {
41 | modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
42 | } else {
43 | modelClass = (Class) BaseViewModel.class;
44 | }
45 | Object object = getViewModelOrFactory();
46 | if (object instanceof BaseViewModel){
47 | mViewModel = (Vm) object;
48 | }else if (object instanceof ViewModelProvider.Factory){
49 | mViewModel = new ViewModelProvider(this, (ViewModelProvider.Factory) object)
50 | .get(modelClass);
51 | }else {
52 | mViewModel = new ViewModelProvider(this,
53 | new ViewModelProvider.NewInstanceFactory()).get(modelClass);
54 | }
55 | }
56 |
57 | protected abstract Object getViewModelOrFactory();
58 |
59 | protected abstract int getViewModelVariable();
60 |
61 | protected abstract void initObservable(Vm viewModel);
62 |
63 | protected abstract void loadData(Vm viewModel);
64 |
65 | protected Vm getViewModel() {
66 | return mViewModel;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/ui/BaseMvvmFragment.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.ui;
2 |
3 | import android.os.Bundle;
4 | import android.view.LayoutInflater;
5 | import android.view.View;
6 | import android.view.ViewGroup;
7 |
8 | import androidx.annotation.NonNull;
9 | import androidx.annotation.Nullable;
10 | import androidx.databinding.ViewDataBinding;
11 | import androidx.lifecycle.ViewModel;
12 | import androidx.lifecycle.ViewModelProvider;
13 | import androidx.lifecycle.ViewModelStoreOwner;
14 |
15 | import com.mvvm.fwk.utils.LogUtils;
16 | import com.mvvm.fwk.viewmodel.BaseViewModel;
17 |
18 | import java.lang.reflect.ParameterizedType;
19 | import java.lang.reflect.Type;
20 |
21 | public abstract class BaseMvvmFragment extends BaseBindingFragment {
22 |
23 | protected Vm mViewModel;
24 |
25 | @Nullable
26 | @Override
27 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
28 | initViewModel();
29 | View view = super.onCreateView(inflater, container, savedInstanceState);
30 | initObservable(mViewModel);
31 | if (getViewModelVariable() != 0) {
32 | mBinding.setVariable(getViewModelVariable(), mViewModel);
33 | }
34 | return view;
35 | }
36 |
37 | @Override
38 | public void onStart() {
39 | super.onStart();
40 | loadData(getViewModel());
41 | }
42 |
43 | private void initViewModel() {
44 | Class modelClass;
45 | Type type = getClass().getGenericSuperclass();
46 | if (type instanceof ParameterizedType) {
47 | modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
48 | } else {
49 | modelClass = (Class) BaseViewModel.class;
50 | }
51 | Object object = getViewModelOrFactory();
52 | if (object instanceof ViewModel){
53 | mViewModel = (Vm) object;
54 | }else if (object instanceof ViewModelProvider.Factory){
55 | mViewModel = new ViewModelProvider(this, (ViewModelProvider.Factory) object)
56 | .get(modelClass);
57 | }else {
58 | mViewModel = new ViewModelProvider(this,
59 | new ViewModelProvider.NewInstanceFactory()).get(modelClass);
60 | }
61 | }
62 |
63 | protected abstract Object getViewModelOrFactory();
64 |
65 | protected abstract int getViewModelVariable();
66 |
67 | protected abstract void initObservable(Vm viewModel);
68 |
69 | protected abstract void loadData(Vm viewModel);
70 |
71 | protected Vm getViewModel() {
72 | return mViewModel;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/utils/LogUtils.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.utils;
2 |
3 | import android.util.Log;
4 |
5 | public class LogUtils {
6 |
7 | public static final String TAG_FWK = "FWK_MVVM_";
8 |
9 | private static boolean DEBUG = true;
10 | private static boolean VERBOSE = true;
11 | private static boolean WARN = true;
12 | private static boolean INFO = true;
13 | private static boolean ERROR = true;
14 |
15 | public static void init(boolean debug, boolean verbose,
16 | boolean warn, boolean info, boolean error) {
17 | DEBUG = debug;
18 | VERBOSE = verbose;
19 | WARN = warn;
20 | INFO = info;
21 | ERROR = error;
22 | }
23 |
24 | /**
25 | * Print debug log info.
26 | *
27 | * @param tag title
28 | * @param info description
29 | */
30 | public static void logD(String tag, String info) {
31 | if (DEBUG) {
32 | Log.d(tag, "[thread:" + Thread.currentThread().getName() + "] - " + info);
33 | StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace();
34 | for (StackTraceElement traceElement : stackTraceElement) {
35 | Log.d(tag, "[thread:" + Thread.currentThread().getName()
36 | + " - class:" + traceElement.getClassName()
37 | + "." + traceElement.getMethodName() + "]");
38 | }
39 | }
40 | }
41 |
42 | /**
43 | * Print verbose log info.
44 | *
45 | * @param tag title
46 | * @param info description
47 | */
48 | public static void logV(String tag, String info) {
49 | if (VERBOSE) {
50 | Log.v(tag, "[thread:" + Thread.currentThread().getName() + "] - " + info);
51 | }
52 | }
53 |
54 | /**
55 | * Print info log info.
56 | *
57 | * @param tag title
58 | * @param info description
59 | */
60 | public static void logI(String tag, String info) {
61 | if (INFO) {
62 | Log.i(tag, "[thread:" + Thread.currentThread().getName() + "] - " + info);
63 | }
64 | }
65 |
66 | /**
67 | * Print warn log info.
68 | *
69 | * @param tag title
70 | * @param info description
71 | */
72 | public static void logW(String tag, String info) {
73 | if (WARN) {
74 | Log.w(tag, "[thread:" + Thread.currentThread().getName() + "] - " + info);
75 | }
76 | }
77 |
78 | /**
79 | * Print error log info.
80 | *
81 | * @param tag title
82 | * @param info description
83 | */
84 | public static void logE(String tag, String info) {
85 | if (ERROR) {
86 | Log.e(tag, "[thread:" + Thread.currentThread().getName() + "] - " + info);
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/AppGlobal.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk;
2 |
3 | import android.app.Application;
4 | import android.content.res.Resources;
5 | import android.graphics.drawable.Drawable;
6 | import android.util.Log;
7 |
8 | import androidx.annotation.ColorRes;
9 | import androidx.annotation.DimenRes;
10 | import androidx.annotation.DrawableRes;
11 | import androidx.annotation.StringRes;
12 | import androidx.core.content.res.ResourcesCompat;
13 |
14 | import java.lang.reflect.InvocationTargetException;
15 | import java.lang.reflect.Method;
16 |
17 | public class AppGlobal {
18 | private static final String TAG = AppGlobal.class.getSimpleName();
19 | public static final String CLASS_FOR_NAME = "android.app.ActivityThread";
20 | public static final String CURRENT_APPLICATION = "currentApplication";
21 | public static final String GET_INITIAL_APPLICATION = "getInitialApplication";
22 |
23 | private AppGlobal() {
24 |
25 | }
26 |
27 | /**
28 | * Get application.
29 | *
30 | * @return application context.
31 | */
32 | public static Application getApplication() {
33 | Application application = null;
34 | try {
35 | Class atClass = Class.forName(CLASS_FOR_NAME);
36 | Method method = atClass.getDeclaredMethod(CURRENT_APPLICATION);
37 | method.setAccessible(true);
38 | application = (Application) method.invoke(null);
39 | } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
40 | | NoSuchMethodException | SecurityException | ClassNotFoundException exception) {
41 | Log.e(TAG, "exception:" + exception.toString());
42 | }
43 |
44 | if (application != null) {
45 | return application;
46 | }
47 |
48 | try {
49 | Class atClass = Class.forName(CLASS_FOR_NAME);
50 | Method method = atClass.getDeclaredMethod(GET_INITIAL_APPLICATION);
51 | method.setAccessible(true);
52 | application = (Application) method.invoke(null);
53 | } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
54 | | NoSuchMethodException | SecurityException | ClassNotFoundException exception) {
55 | Log.e(TAG, "exception:" + exception.toString());
56 | }
57 |
58 | return application;
59 | }
60 |
61 | public static Resources getResource() {
62 | return getApplication().getResources();
63 | }
64 |
65 | public static String getString(@StringRes int resId) {
66 | return getApplication().getResources().getString(resId);
67 | }
68 |
69 | public static int getDimension(@DimenRes int resId) {
70 | return getApplication().getResources().getDimensionPixelOffset(resId);
71 | }
72 |
73 | public static Drawable getDrawable(@DrawableRes int resId) {
74 | return ResourcesCompat.getDrawable(getResource(), resId, null);
75 | }
76 |
77 | public static int getColor(@ColorRes int resId) {
78 | return ResourcesCompat.getColor(getResource(), resId, null);
79 | }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/ui/BaseFragment.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.ui;
2 |
3 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
4 |
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.os.Bundle;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 |
12 | import androidx.annotation.NonNull;
13 | import androidx.annotation.Nullable;
14 | import androidx.fragment.app.Fragment;
15 |
16 | import com.mvvm.fwk.utils.LogUtils;
17 |
18 | public abstract class BaseFragment extends Fragment {
19 |
20 | private final String TAG = TAG_FWK + getClass().getSimpleName();
21 |
22 | @Override
23 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
24 | super.onActivityCreated(savedInstanceState);
25 | LogUtils.logV(TAG, "[onActivityCreated]");
26 | }
27 |
28 | @Override
29 | public void onCreate(@Nullable Bundle savedInstanceState) {
30 | super.onCreate(savedInstanceState);
31 | LogUtils.logV(TAG, "[onCreate]");
32 | }
33 |
34 | @Nullable
35 | @Override
36 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
37 | LogUtils.logV(TAG, "[onCreateView]");
38 | return super.onCreateView(inflater, container, savedInstanceState);
39 | }
40 |
41 | @Override
42 | public void onAttach(@NonNull Context context) {
43 | super.onAttach(context);
44 | LogUtils.logV(TAG, "[onAttach] content " + context);
45 | }
46 |
47 | @Override
48 | public void onAttachFragment(@NonNull Fragment childFragment) {
49 | super.onAttachFragment(childFragment);
50 | LogUtils.logV(TAG, "[onAttachFragment] childFragment " + childFragment);
51 | }
52 |
53 | @Override
54 | public void onStart() {
55 | super.onStart();
56 | LogUtils.logV(TAG, "[onStart]");
57 | }
58 |
59 | @Override
60 | public void onResume() {
61 | super.onResume();
62 | LogUtils.logV(TAG, "[onResume]");
63 | }
64 |
65 | @Override
66 | public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
67 | super.onActivityResult(requestCode, resultCode, data);
68 | LogUtils.logV(TAG, "[onActivityResult] requestCode:" + requestCode + ";"
69 | + "resultCode:" + requestCode);
70 | }
71 |
72 | @Override
73 | public void onPause() {
74 | super.onPause();
75 | LogUtils.logV(TAG, "[onPause]");
76 | }
77 |
78 | @Override
79 | public void onSaveInstanceState(@NonNull Bundle outState) {
80 | super.onSaveInstanceState(outState);
81 | LogUtils.logV(TAG, "[onSaveInstanceState]");
82 | }
83 |
84 | @Override
85 | public void onStop() {
86 | super.onStop();
87 | LogUtils.logV(TAG, "[onStop]");
88 | }
89 |
90 | @Override
91 | public void onDetach() {
92 | super.onDetach();
93 | LogUtils.logV(TAG, "[onDetach]");
94 | }
95 |
96 | @Override
97 | public void onDestroyView() {
98 | super.onDestroyView();
99 | LogUtils.logV(TAG, "[onDestroyView]");
100 | }
101 |
102 | @Override
103 | public void onDestroy() {
104 | super.onDestroy();
105 | LogUtils.logV(TAG, "[onDestroy]");
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/utils/eventbus/StickyLiveData.java:
--------------------------------------------------------------------------------
1 | //
2 | // CONFIDENTIAL - FORD MOTOR COMPANY
3 | //
4 | // This is an unpublished work, which is a trade secret, created in
5 | // 2021. Ford Motor Company owns all rights to this work and intends
6 | // to maintain it in confidence to preserve its trade secret status.
7 | // Ford Motor Company reserves the right to protect this work as an
8 | // unpublished copyrighted work in the event of an inadvertent or
9 | // deliberate unauthorized publication. Ford Motor Company also
10 | // reserves its rights under the copyright laws to protect this work
11 | // as a published work. Those having access to this work may not copy
12 | // it, use it, or disclose the information contained in it without
13 | // the written authorization of Ford Motor Company.
14 | //
15 |
16 | package com.mvvm.fwk.utils.eventbus;
17 |
18 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
19 |
20 | import androidx.annotation.NonNull;
21 | import androidx.lifecycle.Lifecycle;
22 | import androidx.lifecycle.LifecycleEventObserver;
23 | import androidx.lifecycle.LifecycleOwner;
24 | import androidx.lifecycle.LiveData;
25 | import androidx.lifecycle.Observer;
26 |
27 | import com.mvvm.fwk.utils.LogUtils;
28 |
29 | /**
30 | * Custom liveData that support sticky event.
31 | *
32 | * @author WuJia.
33 | * @version 1.0
34 | * @date 2020/10/31
35 | */
36 | public class StickyLiveData extends LiveData {
37 |
38 | private static final String TAG = TAG_FWK + StickyLiveData.class.getSimpleName();
39 |
40 | private IDestroyListener mDestroyListener;
41 |
42 | private final String mChannelName;
43 | private T mStickyData;
44 | private int mVersion = 0;
45 |
46 | public StickyLiveData(String channelName) {
47 | mChannelName = channelName;
48 | }
49 |
50 | @Override
51 | public void setValue(T value) {
52 | mVersion++;
53 | super.setValue(value);
54 | }
55 |
56 | @Override
57 | public void postValue(T value) {
58 | LogUtils.logI(TAG, "postValue::" + value);
59 | mVersion++;
60 | super.postValue(value);
61 | }
62 |
63 | public void setDestroyListener(IDestroyListener destroyListener) {
64 | this.mDestroyListener = destroyListener;
65 | }
66 |
67 | public void setStickyData(T stickyData) {
68 | this.mStickyData = stickyData;
69 | setValue(stickyData);
70 | }
71 |
72 | public void postStickyData(T stickyData) {
73 | this.mStickyData = stickyData;
74 | postValue(stickyData);
75 | }
76 |
77 | @Override
78 | public void observe(@NonNull LifecycleOwner owner, @NonNull Observer super T> observer) {
79 | observerSticky(owner, observer, false);
80 | }
81 |
82 | /**
83 | * Sticky event observer.
84 | *
85 | * @param owner LifecycleOwner
86 | * @param observer LiveData observer
87 | * @param sticky isSticky
88 | */
89 | public void observerSticky(LifecycleOwner owner, Observer super T> observer, boolean sticky) {
90 | super.observe(owner, new WrapperObserver<>(this, observer, sticky));
91 | owner.getLifecycle().addObserver(new LifecycleEventObserver() {
92 | @Override
93 | public void onStateChanged(@NonNull LifecycleOwner source,
94 | @NonNull Lifecycle.Event event) {
95 | if (event == Lifecycle.Event.ON_DESTROY) {
96 | if (mDestroyListener != null) {
97 | mDestroyListener.onLiveDataDestroy(mChannelName);
98 | }
99 | }
100 | }
101 | });
102 | }
103 |
104 | private static class WrapperObserver implements Observer {
105 | private final StickyLiveData mLiveData;
106 | private final Observer mObserver;
107 | private final boolean mSticky;
108 | private int mLastVersion;
109 |
110 | public WrapperObserver(StickyLiveData liveData, Observer observer, boolean sticky) {
111 | mLiveData = liveData;
112 | mObserver = observer;
113 | mSticky = sticky;
114 | mLastVersion = mLiveData.mVersion;
115 | }
116 |
117 | @Override
118 | public void onChanged(T t) {
119 | if (mLastVersion >= mLiveData.mVersion) {
120 | if (mSticky && mLiveData.mStickyData != null) {
121 | mObserver.onChanged(mLiveData.mStickyData);
122 | }
123 | return;
124 | }
125 | mLastVersion = mLiveData.mVersion;
126 | mObserver.onChanged(t);
127 | }
128 | }
129 |
130 | public interface IDestroyListener {
131 |
132 | /**
133 | * Call back when liveData destroy.
134 | *
135 | * @param channelName channel name
136 | */
137 | void onLiveDataDestroy(String channelName);
138 |
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/car_hmi/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/lib_mvvm_fwk/src/main/java/com/mvvm/fwk/utils/AppExecutors.java:
--------------------------------------------------------------------------------
1 | package com.mvvm.fwk.utils;
2 |
3 | import static com.mvvm.fwk.utils.LogUtils.TAG_FWK;
4 |
5 | import android.os.Handler;
6 | import android.os.Looper;
7 | import android.util.Log;
8 |
9 | import androidx.annotation.IntRange;
10 |
11 | import java.util.concurrent.Executor;
12 | import java.util.concurrent.Executors;
13 | import java.util.concurrent.PriorityBlockingQueue;
14 | import java.util.concurrent.ThreadFactory;
15 | import java.util.concurrent.ThreadPoolExecutor;
16 | import java.util.concurrent.TimeUnit;
17 | import java.util.concurrent.atomic.AtomicLong;
18 | import java.util.concurrent.locks.Condition;
19 | import java.util.concurrent.locks.ReentrantLock;
20 |
21 | public class AppExecutors {
22 | private static final String TAG = TAG_FWK + AppExecutors.class.getSimpleName();
23 |
24 | private static final AppExecutors APP_EXECUTORS = new AppExecutors();
25 | public static final long KEEP_ALIVE = 30L;
26 | public static final int MAX_PRIORITY = 10;
27 | public static final int MIN_PRIORITY = 0;
28 | public static final int MIDDLE_PRIORITY = 5;
29 |
30 | private boolean mIsPause;
31 | private final ThreadPoolExecutor mPoolExecutor;
32 | private final ReentrantLock mLock = new ReentrantLock();
33 | private final Condition mPauseCondition;
34 | private final Handler mMainHandler;
35 |
36 | public AppExecutors() {
37 | mMainHandler = new Handler(Looper.getMainLooper());
38 | mPauseCondition = mLock.newCondition();
39 | int cpuCount = Runtime.getRuntime().availableProcessors();
40 | int corePoolSize = cpuCount + 1;
41 | int maxPoolSize = Integer.MAX_VALUE;
42 | PriorityBlockingQueue blockingQueue = new PriorityBlockingQueue<>();
43 |
44 | AtomicLong seq = new AtomicLong();
45 |
46 | ThreadFactory factory = runnable -> {
47 | Thread thread = new Thread(runnable);
48 | thread.setName("FWK_TASK#" + seq.getAndIncrement());
49 | return thread;
50 | };
51 |
52 | mPoolExecutor = new ThreadPoolExecutor(
53 | corePoolSize, maxPoolSize, KEEP_ALIVE, TimeUnit.SECONDS, blockingQueue, factory) {
54 | @Override
55 | protected void beforeExecute(Thread t, Runnable r) {
56 | super.beforeExecute(t, r);
57 | if (mIsPause) {
58 | mLock.lock();
59 | try {
60 | mPauseCondition.await();
61 | } catch (InterruptedException exception) {
62 | LogUtils.logE(TAG, "beforeExecute:" + exception.toString());
63 | } finally {
64 | mLock.unlock();
65 | }
66 | }
67 | }
68 |
69 | @Override
70 | protected void afterExecute(Runnable r, Throwable t) {
71 | super.afterExecute(r, t);
72 | LogUtils.logV(TAG, "this thread priority is " + ((PriorityRunnable) r).mPriority);
73 | }
74 | };
75 |
76 | }
77 |
78 | public static AppExecutors get() {
79 | return APP_EXECUTORS;
80 | }
81 |
82 | public void execute(@IntRange(from = MIN_PRIORITY, to = MAX_PRIORITY) int priority,
83 | Runnable runnable) {
84 | mPoolExecutor.execute(new PriorityRunnable(priority, runnable));
85 | }
86 |
87 | public void execute(Runnable runnable) {
88 | execute(MIDDLE_PRIORITY, runnable);
89 | }
90 |
91 | public void post(Runnable runnable) {
92 | mMainHandler.post(runnable);
93 | }
94 |
95 | public void postDelay(Runnable runnable, long delayMills) {
96 | mMainHandler.postDelayed(runnable, delayMills);
97 | }
98 |
99 | public void postRemove(Runnable runnable) {
100 | mMainHandler.removeCallbacks(runnable);
101 | }
102 |
103 | /**
104 | * Pause thread pool.
105 | */
106 | public void pause() {
107 | mLock.lock();
108 | try {
109 | mIsPause = true;
110 | LogUtils.logW(TAG, "thread pool is paused");
111 | } finally {
112 | mLock.unlock();
113 | }
114 | }
115 |
116 | /**
117 | * Resume thread pool.
118 | */
119 | public void resume() {
120 | mLock.lock();
121 | try {
122 | mIsPause = false;
123 | mPauseCondition.signalAll();
124 | } finally {
125 | mLock.unlock();
126 | }
127 | LogUtils.logW(TAG, "thread pool is resumed");
128 | }
129 |
130 | private static class MainThreadExecutor implements Executor {
131 | private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
132 |
133 | public void removeCallbacksAndMessages(Object token) {
134 | mMainThreadHandler.removeCallbacksAndMessages(token);
135 | }
136 |
137 | @Override
138 | public void execute(Runnable runnable) {
139 | mMainThreadHandler.post(runnable);
140 | }
141 | }
142 |
143 | public abstract class Callable implements Runnable {
144 |
145 | @Override
146 | public void run() {
147 | mMainHandler.post(this::onPrepare);
148 | T background = onBackground();
149 | mMainHandler.removeCallbacksAndMessages(null);
150 | mMainHandler.post(() -> onCompleted(background));
151 | }
152 |
153 | protected void onPrepare() {
154 | // do nothing.
155 | }
156 |
157 | protected abstract T onBackground();
158 |
159 | protected abstract void onCompleted(T background);
160 | }
161 |
162 | public static class PriorityRunnable implements Runnable, Comparable {
163 |
164 | private final int mPriority;
165 | private final Runnable mRunnable;
166 |
167 | public PriorityRunnable(int priority, Runnable runnable) {
168 | mPriority = priority;
169 | mRunnable = runnable;
170 | }
171 |
172 | @Override
173 | public int compareTo(PriorityRunnable runnable) {
174 | return Integer.compare(runnable.mPriority, this.mPriority);
175 | }
176 |
177 | @Override
178 | public void run() {
179 | mRunnable.run();
180 | }
181 | }
182 |
183 | }
184 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Android 车载应用开发与分析 (3)- HMI 构建 MVVM 架构(Java版)
2 |
3 | ## 前言
4 |
5 | 在大多数车载系统应用架构中,一个完整的应用往往会包含三层:
6 |
7 | * **HMI**
8 | Human Machine Interface,显示UI信息,进行人机交互。
9 |
10 | * **Service**
11 | 在系统后台进行数据处理,监控数据状态。
12 |
13 | * **SDK**
14 | 根据业务逻辑`Service`对外暴露的通信接口,其他模块通过它来完成IPC通信。
15 |
16 | 当然并不是所有的应用都需要`Service`,只有不能长久的驻留在内存中,且需要监控系统数据和行为的应用才需要`Service`。
17 |
18 | 举个例子,系统的**OTA**需要一个`Service`在IVI的后台监控云服务或SOA接口的消息,然后完成升级包的下载等。也需要一个`HMI`显示升级的Release Note、确认用户是否同意升级等,这个HMI往往会被归纳在系统设置中。`Service`与`HMI`之间的IPC通信,则需要暴露一个`SDK`来完成,这个其他模块的`HMI`也可以通过这个`SDK`完成与`Service`的IPC通信。
19 |
20 | 反例则是,**Launcher** 可以长久的驻留在内存,所以它也就不需要`Service`和`SDK`。
21 |
22 | **本篇文章主要讲解,如在HMI层中构建一个适合车载系统应用的MVVM架构。本文涉及的源码:https://github.com/linux-link/CarMvvmArch**
23 |
24 | ## MVVM 架构分层逻辑
25 |
26 | **MVVM** 架构的原理以及与MVC&MVP的区别,网上已经有很多相关的优秀文章,这里就不再赘述,本篇文章将聚焦如何车载应用中利用Jetpack组件将 **MVVM** 架构真正落地实现。
27 |
28 | 
29 |
30 | 当前的Android应用的**MVVM**架构分层逻辑,都源自图-2 Android官方给出的指导建议,我们也同样基于这套逻辑来实现**MVVM**架构。
31 |
32 | 
33 |
34 | ## 封装适合车载应用 MVVM 框架
35 |
36 | **车载应用**相对于**手机应用**来说开发周期和复杂度都要小很多,所以我们封装的重点是**View**层,**ViewModel** 层和 **Model** 层的封装则会简单很多。
37 |
38 | ### 封装 Model 层
39 |
40 | 一般来说我们会把访问网络的工具类封装在Model层,但是车载系统应用的 **HMI** 层通常没有访问网络的功能,所以 **Model** 层我们直接留空即可。
41 |
42 | ```
43 | public abstract class BaseRepository {
44 |
45 | }
46 |
47 | ```
48 |
49 | ### 封装 ViewModel 层
50 |
51 | **VideModel** 层的封装很简单,只需要将Model的实例传入,方便 **ViewModel** 的实现类调用即可。
52 |
53 | **封装 ViewModel**
54 |
55 | ```
56 | public abstract class BaseViewModel extends ViewModel {
57 |
58 | protected M mRepository;
59 |
60 | public BaseViewModel(M repository) {
61 | mRepository = repository;
62 | }
63 |
64 | public M getRepository() {
65 | return mRepository;
66 | }
67 | }
68 |
69 | ```
70 |
71 | **封装 AndroidViewModel**
72 |
73 | ```
74 | public abstract class BaseAndroidViewModel extends AndroidViewModel {
75 |
76 | protected M mRepository;
77 |
78 | public BaseAndroidViewModel(Application application, @Nullable M repository) {
79 | super(application);
80 | mRepository = repository;
81 | }
82 |
83 | public M getRepository() {
84 | return mRepository;
85 | }
86 | }
87 |
88 | ```
89 |
90 | ### 封装 View 层
91 |
92 | **在 View** 层中我们需要引入`Databinding`和`ViewModel`,并且定义出 **View** 的一些实现规范。
93 |
94 | 在实际使用中,并不是每一个界面都需要使用**MVVM**架构, 所以需要额外封装一个只引入`Databinding`的 **Frangment** 和 **Activity**
95 |
96 | **基于 DataBinding 封装 Fragment**
97 |
98 | ```
99 | public abstract class BaseBindingFragment extends BaseFragment {
100 |
101 | private static final String TAG = TAG_FWK + BaseBindingFragment.class.getSimpleName();
102 |
103 | protected V mBinding;
104 |
105 | @Nullable
106 | @Override
107 | public View onCreateView(@NonNull LayoutInflater inflater,
108 | @Nullable ViewGroup container,
109 | @Nullable Bundle savedInstanceState) {
110 | LogUtils.logV(TAG, "[onCreateView]");
111 | if (getLayoutId() == 0) {
112 | throw new RuntimeException("getLayout() must be not null");
113 | }
114 | mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
115 | mBinding.setLifecycleOwner(this);
116 | mBinding.executePendingBindings();
117 | initView();
118 | return mBinding.getRoot();
119 | }
120 |
121 | protected abstract void initView();
122 |
123 | @LayoutRes
124 | protected abstract int getLayoutId();
125 |
126 | public V getBinding() {
127 | return mBinding;
128 | }
129 | }
130 |
131 | ```
132 |
133 | **在** **BindingFragment** **的基础上添加 ViewModel**
134 |
135 | ```
136 | public abstract class BaseMvvmFragment extends BaseBindingFragment {
137 |
138 | protected Vm mViewModel;
139 |
140 | @Nullable
141 | @Override
142 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
143 | initViewModel();
144 | View view = super.onCreateView(inflater, container, savedInstanceState);
145 | initObservable(mViewModel);
146 | if (getViewModelVariable() != 0) {
147 | mBinding.setVariable(getViewModelVariable(), mViewModel);
148 | }
149 | return view;
150 | }
151 |
152 | @Override
153 | public void onStart() {
154 | super.onStart();
155 | loadData(getViewModel());
156 | }
157 |
158 | private void initViewModel() {
159 | Class modelClass;
160 | Type type = getClass().getGenericSuperclass();
161 | if (type instanceof ParameterizedType) {
162 | modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
163 | } else {
164 | modelClass = (Class) BaseViewModel.class;
165 | }
166 | Object object = getViewModelOrFactory();
167 | if (object instanceof ViewModel){
168 | mViewModel = (Vm) object;
169 | }else if (object instanceof ViewModelProvider.Factory){
170 | mViewModel = new ViewModelProvider(this, (ViewModelProvider.Factory) object)
171 | .get(modelClass);
172 | }else {
173 | mViewModel = new ViewModelProvider(this,
174 | new ViewModelProvider.NewInstanceFactory()).get(modelClass);
175 | }
176 | }
177 |
178 | protected abstract Object getViewModelOrFactory();
179 |
180 | protected abstract int getViewModelVariable();
181 |
182 | protected abstract void initObservable(Vm viewModel);
183 |
184 | protected abstract void loadData(Vm viewModel);
185 |
186 | protected Vm getViewModel() {
187 | return mViewModel;
188 | }
189 | }
190 |
191 | ```
192 |
193 | **基于 DataBinding 封装 Activity**
194 |
195 | ```
196 | public abstract class BaseBindingActivity extends BaseActivity {
197 |
198 | protected V mBinding;
199 |
200 | @Override
201 | protected void onCreate(@Nullable Bundle savedInstanceState) {
202 | super.onCreate(savedInstanceState);
203 | if (getLayoutId() == 0) {
204 | throw new RuntimeException("getLayout() must be not null");
205 | }
206 | mBinding = DataBindingUtil.setContentView(this, getLayoutId());
207 | mBinding.setLifecycleOwner(this);
208 | mBinding.executePendingBindings();
209 | initView();
210 | }
211 |
212 | @LayoutRes
213 | protected abstract int getLayoutId();
214 |
215 | public V getBinding() {
216 | return mBinding;
217 | }
218 |
219 | protected abstract void initView();
220 | }
221 |
222 | ```
223 |
224 | **在 BindingActivity 的基础上添加 ViewModel**
225 |
226 | ```
227 | public abstract class BaseMvvmActivity extends BaseBindingActivity {
228 |
229 | protected Vm mViewModel;
230 |
231 | @Override
232 | protected void onCreate(@Nullable Bundle savedInstanceState) {
233 | initViewModel();
234 | super.onCreate(savedInstanceState);
235 | if (getViewModelVariable() != 0) {
236 | mBinding.setVariable(getViewModelVariable(), mViewModel);
237 | }
238 | mBinding.executePendingBindings();
239 | initObservable(mViewModel);
240 | }
241 |
242 | @Override
243 | protected void onStart() {
244 | super.onStart();
245 | loadData(mViewModel);
246 | }
247 |
248 | private void initViewModel() {
249 | Class modelClass;
250 | Type type = getClass().getGenericSuperclass();
251 | if (type instanceof ParameterizedType) {
252 | modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
253 | } else {
254 | modelClass = (Class) BaseViewModel.class;
255 | }
256 | Object object = getViewModelOrFactory();
257 | if (object instanceof BaseViewModel){
258 | mViewModel = (Vm) object;
259 | }else if (object instanceof ViewModelProvider.Factory){
260 | mViewModel = new ViewModelProvider(this, (ViewModelProvider.Factory) object)
261 | .get(modelClass);
262 | }else {
263 | mViewModel = new ViewModelProvider(this,
264 | new ViewModelProvider.NewInstanceFactory()).get(modelClass);
265 | }
266 | }
267 |
268 | protected abstract Object getViewModelOrFactory();
269 |
270 | protected abstract int getViewModelVariable();
271 |
272 | protected abstract void initObservable(Vm viewModel);
273 |
274 | protected abstract void loadData(Vm viewModel);
275 |
276 | protected Vm getViewModel() {
277 | return mViewModel;
278 | }
279 | }
280 |
281 | ```
282 |
283 | 重点解释一下几个abstract的方法
284 |
285 | * **Object getViewModelOrFactory()**
286 |
287 | 返回ViewModel的实例或ViewModelFactory实例
288 |
289 | * **int getViewModelVariable()**
290 |
291 | 返回XML中ViewModel的**Variable****Id。例如:BR.viewModel.**
292 |
293 | * **void initObservable(Vm viewModel)**
294 |
295 | 在此处操作ViewModel中LiveData的。例如:下面这类方法,都应该写在这个方法体里面。目的是为了便于维护
296 |
297 | ```
298 | viewModel.getTempLive().observe(this, new Observer() {
299 | @Override
300 | public void onChanged(String temp) {
301 | LogUtils.logI(TAG, "[onChanged] " + temp);
302 | }
303 | });
304 |
305 | ```
306 |
307 | * **void initView()**
308 |
309 | 在此处进行初始化UI的操作。例如:初始化RecyclerView,设定ClickListener等等。
310 |
311 | * **void loadData(Vm viewModel)**
312 |
313 | 在此处使用`ViewModel`进行请求用于初始化UI的数据。
314 |
315 | ## 基于框架实现MVVM架构
316 |
317 | 接下来我们基于上面封装的 **MVVM** 框架,来实现一个最基础的 **MVVM** 架构下的demo。
318 |
319 | ### 定义公共组件
320 |
321 | #### 创建 ViewModelFactory
322 |
323 | 定义`ViewModel`的实例化方式,单一Module下`ViewModel`的创建应该集中在一个`ViewModelFactory`中
324 |
325 | ```
326 | // default 权限,不对外部公开此类
327 | class AppViewModelFactory implements ViewModelProvider.Factory {
328 |
329 | // 创建 viewModel 实例
330 | @NonNull
331 | @Override
332 | public T create(@NonNull Class modelClass) {
333 | try {
334 | if (modelClass == HvacViewModel.class) {
335 | return modelClass.getConstructor(HvacRepository.class, AppExecutors.class)
336 | .newInstance(AppInjection.getHvacRepository(), AppExecutors.get());
337 | } else {
338 | throw new RuntimeException(modelClass.getSimpleName() + "create failed");
339 | }
340 | } catch (NoSuchMethodException | IllegalAccessException
341 | | InstantiationException | InvocationTargetException exception) {
342 | exception.printStackTrace();
343 | throw new RuntimeException(exception);
344 | }
345 | }
346 | }
347 |
348 | ```
349 |
350 | #### 创建 AppInjection
351 |
352 | 如果应用中没有使用 **Dagger** 或 **Hilt** 等依赖注入框架,那么为了便于日后的维护,无论是车载应用还是手机应用,都建议定义一个`AppInjection`来将应用中的单例、ViewModel、Repository等实例的获取统一到一个入口程序中。
353 |
354 | ```
355 | public class AppInjection {
356 |
357 | // ViewModel 工厂
358 | private final static AppViewModelFactory mViewModelFactory = new AppViewModelFactory();
359 |
360 | public static T getViewModel(ViewModelStoreOwner store, Class clazz) {
361 | return new ViewModelProvider(store, mViewModelFactory).get(clazz);
362 | }
363 |
364 | public static AppViewModelFactory getViewModelFactory() {
365 | return mViewModelFactory;
366 | }
367 |
368 | /**
369 | * 受保护的权限,除了ViewModel,其它模块不应该需要Model层的实例
370 | *
371 | * @return {@link HvacRepository}
372 | */
373 | protected static HvacRepository getHvacRepository() {
374 | return new HvacRepository(getHvacManager());
375 | }
376 |
377 | public static HvacManager getHvacManager() {
378 | return HvacManager.getInstance();
379 | }
380 |
381 | }
382 |
383 | ```
384 |
385 | ### 构建 Model 层
386 |
387 | 在车载应用中 **Model** 层的主要数据源无外乎 有三种**网络数据源**、**HMI本地数据源**、**IPC(进程间通信)数据源**,其中最常见的是只有**IPC数据源,**三种数据源都有的情况往往会出现在主机厂商自行开发的**车载地图应用**中。所以我们这里只考虑如何基于**IPC数据源**构造**Model**层
388 |
389 | 定义一个 `XXX``Repository` 继承自 `BaseRepository`,再根据业务需要定义出我们需要使用的接口,这里的`HvacManager`就是**service**提供的用来进行跨进程通信的**IPC-SDK**中的入口。
390 |
391 | ```
392 | public class HvacRepository extends BaseRepository {
393 |
394 | private static final String TAG = IpcApp.TAG_HVAC + HvacRepository.class.getSimpleName();
395 |
396 | private final HvacManager mHvacManager;
397 | private HvacCallback mHvacViewModelCallback;
398 |
399 | private final IHvacCallback mHvacCallback = new IHvacCallback() {
400 | @Override
401 | public void onTemperatureChanged(double temp) {
402 | if (mHvacViewModelCallback != null) {
403 | // 处理远程数据,讲他转换为应用中需要的数据格式或内容
404 | String value = String.valueOf(temp);
405 | mHvacViewModelCallback.onTemperatureChanged(value);
406 | }
407 | }
408 | };
409 |
410 | public HvacRepository(HvacManager hvacManager) {
411 | mHvacManager = hvacManager;
412 | mHvacManager.registerCallback(mHvacCallback);
413 | }
414 |
415 | public void clear() {
416 | mHvacManager.unregisterCallback(mHvacCallback);
417 | }
418 |
419 | public void requestTemperature() {
420 | LogUtils.logI(TAG, "[requestTemperature]");
421 | mHvacManager.requestTemperature();
422 | }
423 |
424 | public void setTemperature(int temperature) {
425 | LogUtils.logI(TAG, "[setTemperature] " + temperature);
426 | mHvacManager.setTemperature(temperature);
427 | }
428 |
429 | public void setHvacListener(HvacCallback callback) {
430 | LogUtils.logI(TAG, "[setHvacListener] " + callback);
431 | mHvacViewModelCallback = callback;
432 | }
433 |
434 | public void removeHvacListener(HvacCallback callback) {
435 | LogUtils.logI(TAG, "[removeHvacListener] " + callback);
436 | mHvacViewModelCallback = null;
437 | }
438 |
439 | }
440 |
441 | ```
442 |
443 | `Repository`通过一个`HvacCallback`将监听的远程数据处理后返回给`ViewModel`。
444 |
445 | > 如果应用会与多个不同的模块进行IPC通信,那么建议将这些由不同模块提供的**IPC-SDK**封装在一个Manager中进行统一管理。
446 |
447 | ### 构建ViewModel
448 |
449 | 在Jetpack中`ViewModel`的用途是封装界面控制器的数据,以使数据在配置更改后仍然存在。在Android的**MVVM** 架构设计中,`ViewModel`是最关键的一层,通过持有`Repository`的引用来进行外部通信
450 |
451 | ```
452 | public class HvacViewModel extends BaseViewModel {
453 |
454 | private static final String TAG = IpcApp.TAG_HVAC + HvacViewModel.class.getSimpleName();
455 |
456 | private final HvacRepository mRepository;
457 | // 线程池框架。某些场景,ViewModel访问Repository中的方法可能会需要切换到子线程。
458 | private final AppExecutors mAppExecutors;
459 | private MutableLiveData mTempLive;
460 |
461 | private final HvacCallback mHvacCallback = new HvacCallback() {
462 | @Override
463 | public void onTemperatureChanged(String temp) {
464 | LogUtils.logI(TAG, "[onTemperatureChanged] " + temp);
465 | getTempLive().postValue(temp);
466 | }
467 | };
468 |
469 | public HvacViewModel(HvacRepository repository, AppExecutors executors) {
470 | super(repository);
471 | mRepository = repository;
472 | mAppExecutors = executors;
473 | mRepository.setHvacListener(mHvacCallback);
474 | }
475 |
476 | @Override
477 | protected void onCleared() {
478 | super.onCleared();
479 | mRepository.removeHvacListener(mHvacCallback);
480 | mRepository.release();
481 | }
482 |
483 | /**
484 | * 请求页面数据
485 | */
486 | public void requestTemperature() {
487 | mRepository.requestTemperature();
488 | }
489 |
490 | /**
491 | * 将温度数据设定到Service中
492 | *
493 | * @param view
494 | */
495 | public void setTemperature(View view) {
496 | mRepository.setTemperature(getTempLive().getValue());
497 | }
498 |
499 | public MutableLiveData getTempLive() {
500 | if (mTempLive == null) {
501 | mTempLive = new MutableLiveData<>();
502 | }
503 | return mTempLive;
504 | }
505 | }
506 |
507 | ```
508 |
509 | ### 构建View层
510 |
511 | 最后就是构建View层,一把就是Activity/Fragment和XML。
512 |
513 | `HvacActivity`中各个方法含义我们上面封装BaseMvvmActivity的时候已经解释过了,这里不再赘述。
514 |
515 | ```
516 | public class HvacActivity extends BaseMvvmActivity {
517 |
518 | private static final String TAG = IpcApp.TAG_HVAC + HvacActivity.class.getSimpleName();
519 |
520 | @Override
521 | protected int getLayoutId() {
522 | return R.layout.activity_hvac;
523 | }
524 |
525 | @Override
526 | protected Object getViewModelOrFactory() {
527 | return AppInjection.getViewModelFactory();
528 | }
529 |
530 | @Override
531 | protected int getViewModelVariable() {
532 | return BR.viewModel;
533 | }
534 |
535 | @Override
536 | protected void initView() {
537 |
538 | }
539 |
540 | @Override
541 | protected void initObservable(HvacViewModel viewModel) {
542 | viewModel.getTempLive().observe(this, new Observer() {
543 | @Override
544 | public void onChanged(String temp) {
545 | LogUtils.logI(TAG, "[onChanged] " + temp);
546 | }
547 | });
548 | }
549 |
550 | @Override
551 | protected void loadData(HvacViewModel viewModel) {
552 | viewModel.requestTemperature();
553 | }
554 | }
555 |
556 | ```
557 |
558 | ```
559 |
560 |
563 |
564 |
565 |
566 |
569 |
570 |
571 |
574 |
575 |
586 |
587 |
596 |
597 |
606 |
607 |
608 |
609 |
610 | ```
611 |
612 | 以上就是如何封装一个适合车载应用使用的 **MVVM** 框架。不知道你有没有发现,在HMI中使用AIDL方法。通常是比较麻烦的。我们需要在HMI与Service完成绑定后,我们才能调用Service中实现的Binder方法。但是示例中我们使用的SDK,并没进行绑定操作,而是直接进行调用。关于如何编写基于AIDL的SDK,就放到下一章再介绍,感谢您的阅读。
613 |
614 | 本文所涉及的源码请访问:**https://github.com/linux-link/CarMvvmArch**
615 |
616 | ## 参考资料
617 |
618 | [应用架构指南 | Android 开发者 | Android Developers](https://developer.android.google.cn/jetpack/guide?hl=zh_cn)
619 | Android 车载应用开发与分析 (3)- HMI 构建 MVVM 架构(Java版)
620 |
621 | ## 前言
622 |
623 | 在大多数车载系统应用架构中,一个完整的应用往往会包含三层:
624 |
625 | * **HMI**
626 | Human Machine Interface,显示UI信息,进行人机交互。
627 |
628 | * **Service**
629 | 在系统后台进行数据处理,监控数据状态。
630 |
631 | * **SDK**
632 | 根据业务逻辑`Service`对外暴露的通信接口,其他模块通过它来完成IPC通信。
633 |
634 | 当然并不是所有的应用都需要`Service`,只有不能长久的驻留在内存中,且需要监控系统数据和行为的应用才需要`Service`。
635 |
636 | 举个例子,系统的**OTA**需要一个`Service`在IVI的后台监控云服务或SOA接口的消息,然后完成升级包的下载等。也需要一个`HMI`显示升级的Release Note、确认用户是否同意升级等,这个HMI往往会被归纳在系统设置中。`Service`与`HMI`之间的IPC通信,则需要暴露一个`SDK`来完成,这个其他模块的`HMI`也可以通过这个`SDK`完成与`Service`的IPC通信。
637 |
638 | 反例则是,**Launcher** 可以长久的驻留在内存,所以它也就不需要`Service`和`SDK`。
639 |
640 | **本篇文章主要讲解,如在HMI层中构建一个适合车载系统应用的MVVM架构。本文涉及的源码:https://github.com/linux-link/CarMvvmArch**
641 |
642 | ## MVVM 架构分层逻辑
643 |
644 | **MVVM** 架构的原理以及与MVC&MVP的区别,网上已经有很多相关的优秀文章,这里就不再赘述,本篇文章将聚焦如何车载应用中利用Jetpack组件将 **MVVM** 架构真正落地实现。
645 |
646 | 
647 |
648 | 当前的Android应用的**MVVM**架构分层逻辑,都源自图-2 Android官方给出的指导建议,我们也同样基于这套逻辑来实现**MVVM**架构。
649 |
650 | 
651 |
652 | ## 封装适合车载应用 MVVM 框架
653 |
654 | **车载应用**相对于**手机应用**来说开发周期和复杂度都要小很多,所以我们封装的重点是**View**层,**ViewModel** 层和 **Model** 层的封装则会简单很多。
655 |
656 | ### 封装 Model 层
657 |
658 | 一般来说我们会把访问网络的工具类封装在Model层,但是车载系统应用的 **HMI** 层通常没有访问网络的功能,所以 **Model** 层我们直接留空即可。
659 |
660 | ```
661 | public abstract class BaseRepository {
662 |
663 | }
664 |
665 | ```
666 |
667 | ### 封装 ViewModel 层
668 |
669 | **VideModel** 层的封装很简单,只需要将Model的实例传入,方便 **ViewModel** 的实现类调用即可。
670 |
671 | **封装 ViewModel**
672 |
673 | ```
674 | public abstract class BaseViewModel extends ViewModel {
675 |
676 | protected M mRepository;
677 |
678 | public BaseViewModel(M repository) {
679 | mRepository = repository;
680 | }
681 |
682 | public M getRepository() {
683 | return mRepository;
684 | }
685 | }
686 |
687 | ```
688 |
689 | **封装 AndroidViewModel**
690 |
691 | ```
692 | public abstract class BaseAndroidViewModel extends AndroidViewModel {
693 |
694 | protected M mRepository;
695 |
696 | public BaseAndroidViewModel(Application application, @Nullable M repository) {
697 | super(application);
698 | mRepository = repository;
699 | }
700 |
701 | public M getRepository() {
702 | return mRepository;
703 | }
704 | }
705 |
706 | ```
707 |
708 | ### 封装 View 层
709 |
710 | **在 View** 层中我们需要引入`Databinding`和`ViewModel`,并且定义出 **View** 的一些实现规范。
711 |
712 | 在实际使用中,并不是每一个界面都需要使用**MVVM**架构, 所以需要额外封装一个只引入`Databinding`的 **Frangment** 和 **Activity**
713 |
714 | **基于 DataBinding 封装 Fragment**
715 |
716 | ```
717 | public abstract class BaseBindingFragment extends BaseFragment {
718 |
719 | private static final String TAG = TAG_FWK + BaseBindingFragment.class.getSimpleName();
720 |
721 | protected V mBinding;
722 |
723 | @Nullable
724 | @Override
725 | public View onCreateView(@NonNull LayoutInflater inflater,
726 | @Nullable ViewGroup container,
727 | @Nullable Bundle savedInstanceState) {
728 | LogUtils.logV(TAG, "[onCreateView]");
729 | if (getLayoutId() == 0) {
730 | throw new RuntimeException("getLayout() must be not null");
731 | }
732 | mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
733 | mBinding.setLifecycleOwner(this);
734 | mBinding.executePendingBindings();
735 | initView();
736 | return mBinding.getRoot();
737 | }
738 |
739 | protected abstract void initView();
740 |
741 | @LayoutRes
742 | protected abstract int getLayoutId();
743 |
744 | public V getBinding() {
745 | return mBinding;
746 | }
747 | }
748 |
749 | ```
750 |
751 | **在** **BindingFragment** **的基础上添加 ViewModel**
752 |
753 | ```
754 | public abstract class BaseMvvmFragment extends BaseBindingFragment {
755 |
756 | protected Vm mViewModel;
757 |
758 | @Nullable
759 | @Override
760 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
761 | initViewModel();
762 | View view = super.onCreateView(inflater, container, savedInstanceState);
763 | initObservable(mViewModel);
764 | if (getViewModelVariable() != 0) {
765 | mBinding.setVariable(getViewModelVariable(), mViewModel);
766 | }
767 | return view;
768 | }
769 |
770 | @Override
771 | public void onStart() {
772 | super.onStart();
773 | loadData(getViewModel());
774 | }
775 |
776 | private void initViewModel() {
777 | Class modelClass;
778 | Type type = getClass().getGenericSuperclass();
779 | if (type instanceof ParameterizedType) {
780 | modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
781 | } else {
782 | modelClass = (Class) BaseViewModel.class;
783 | }
784 | Object object = getViewModelOrFactory();
785 | if (object instanceof ViewModel){
786 | mViewModel = (Vm) object;
787 | }else if (object instanceof ViewModelProvider.Factory){
788 | mViewModel = new ViewModelProvider(this, (ViewModelProvider.Factory) object)
789 | .get(modelClass);
790 | }else {
791 | mViewModel = new ViewModelProvider(this,
792 | new ViewModelProvider.NewInstanceFactory()).get(modelClass);
793 | }
794 | }
795 |
796 | protected abstract Object getViewModelOrFactory();
797 |
798 | protected abstract int getViewModelVariable();
799 |
800 | protected abstract void initObservable(Vm viewModel);
801 |
802 | protected abstract void loadData(Vm viewModel);
803 |
804 | protected Vm getViewModel() {
805 | return mViewModel;
806 | }
807 | }
808 |
809 | ```
810 |
811 | **基于 DataBinding 封装 Activity**
812 |
813 | ```
814 | public abstract class BaseBindingActivity extends BaseActivity {
815 |
816 | protected V mBinding;
817 |
818 | @Override
819 | protected void onCreate(@Nullable Bundle savedInstanceState) {
820 | super.onCreate(savedInstanceState);
821 | if (getLayoutId() == 0) {
822 | throw new RuntimeException("getLayout() must be not null");
823 | }
824 | mBinding = DataBindingUtil.setContentView(this, getLayoutId());
825 | mBinding.setLifecycleOwner(this);
826 | mBinding.executePendingBindings();
827 | initView();
828 | }
829 |
830 | @LayoutRes
831 | protected abstract int getLayoutId();
832 |
833 | public V getBinding() {
834 | return mBinding;
835 | }
836 |
837 | protected abstract void initView();
838 | }
839 |
840 | ```
841 |
842 | **在 BindingActivity 的基础上添加 ViewModel**
843 |
844 | ```
845 | public abstract class BaseMvvmActivity extends BaseBindingActivity {
846 |
847 | protected Vm mViewModel;
848 |
849 | @Override
850 | protected void onCreate(@Nullable Bundle savedInstanceState) {
851 | initViewModel();
852 | super.onCreate(savedInstanceState);
853 | if (getViewModelVariable() != 0) {
854 | mBinding.setVariable(getViewModelVariable(), mViewModel);
855 | }
856 | mBinding.executePendingBindings();
857 | initObservable(mViewModel);
858 | }
859 |
860 | @Override
861 | protected void onStart() {
862 | super.onStart();
863 | loadData(mViewModel);
864 | }
865 |
866 | private void initViewModel() {
867 | Class modelClass;
868 | Type type = getClass().getGenericSuperclass();
869 | if (type instanceof ParameterizedType) {
870 | modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
871 | } else {
872 | modelClass = (Class) BaseViewModel.class;
873 | }
874 | Object object = getViewModelOrFactory();
875 | if (object instanceof BaseViewModel){
876 | mViewModel = (Vm) object;
877 | }else if (object instanceof ViewModelProvider.Factory){
878 | mViewModel = new ViewModelProvider(this, (ViewModelProvider.Factory) object)
879 | .get(modelClass);
880 | }else {
881 | mViewModel = new ViewModelProvider(this,
882 | new ViewModelProvider.NewInstanceFactory()).get(modelClass);
883 | }
884 | }
885 |
886 | protected abstract Object getViewModelOrFactory();
887 |
888 | protected abstract int getViewModelVariable();
889 |
890 | protected abstract void initObservable(Vm viewModel);
891 |
892 | protected abstract void loadData(Vm viewModel);
893 |
894 | protected Vm getViewModel() {
895 | return mViewModel;
896 | }
897 | }
898 |
899 | ```
900 |
901 | 重点解释一下几个abstract的方法
902 |
903 | * **Object getViewModelOrFactory()**
904 |
905 | 返回ViewModel的实例或ViewModelFactory实例
906 |
907 | * **int getViewModelVariable()**
908 |
909 | 返回XML中ViewModel的**Variable****Id。例如:BR.viewModel.**
910 |
911 | * **void initObservable(Vm viewModel)**
912 |
913 | 在此处操作ViewModel中LiveData的。例如:下面这类方法,都应该写在这个方法体里面。目的是为了便于维护
914 |
915 | ```
916 | viewModel.getTempLive().observe(this, new Observer() {
917 | @Override
918 | public void onChanged(String temp) {
919 | LogUtils.logI(TAG, "[onChanged] " + temp);
920 | }
921 | });
922 |
923 | ```
924 |
925 | * **void initView()**
926 |
927 | 在此处进行初始化UI的操作。例如:初始化RecyclerView,设定ClickListener等等。
928 |
929 | * **void loadData(Vm viewModel)**
930 |
931 | 在此处使用`ViewModel`进行请求用于初始化UI的数据。
932 |
933 | ## 基于框架实现MVVM架构
934 |
935 | 接下来我们基于上面封装的 **MVVM** 框架,来实现一个最基础的 **MVVM** 架构下的demo。
936 |
937 | ### 定义公共组件
938 |
939 | #### 创建 ViewModelFactory
940 |
941 | 定义`ViewModel`的实例化方式,单一Module下`ViewModel`的创建应该集中在一个`ViewModelFactory`中
942 |
943 | ```
944 | // default 权限,不对外部公开此类
945 | class AppViewModelFactory implements ViewModelProvider.Factory {
946 |
947 | // 创建 viewModel 实例
948 | @NonNull
949 | @Override
950 | public T create(@NonNull Class modelClass) {
951 | try {
952 | if (modelClass == HvacViewModel.class) {
953 | return modelClass.getConstructor(HvacRepository.class, AppExecutors.class)
954 | .newInstance(AppInjection.getHvacRepository(), AppExecutors.get());
955 | } else {
956 | throw new RuntimeException(modelClass.getSimpleName() + "create failed");
957 | }
958 | } catch (NoSuchMethodException | IllegalAccessException
959 | | InstantiationException | InvocationTargetException exception) {
960 | exception.printStackTrace();
961 | throw new RuntimeException(exception);
962 | }
963 | }
964 | }
965 |
966 | ```
967 |
968 | #### 创建 AppInjection
969 |
970 | 如果应用中没有使用 **Dagger** 或 **Hilt** 等依赖注入框架,那么为了便于日后的维护,无论是车载应用还是手机应用,都建议定义一个`AppInjection`来将应用中的单例、ViewModel、Repository等实例的获取统一到一个入口程序中。
971 |
972 | ```
973 | public class AppInjection {
974 |
975 | // ViewModel 工厂
976 | private final static AppViewModelFactory mViewModelFactory = new AppViewModelFactory();
977 |
978 | public static T getViewModel(ViewModelStoreOwner store, Class clazz) {
979 | return new ViewModelProvider(store, mViewModelFactory).get(clazz);
980 | }
981 |
982 | public static AppViewModelFactory getViewModelFactory() {
983 | return mViewModelFactory;
984 | }
985 |
986 | /**
987 | * 受保护的权限,除了ViewModel,其它模块不应该需要Model层的实例
988 | *
989 | * @return {@link HvacRepository}
990 | */
991 | protected static HvacRepository getHvacRepository() {
992 | return new HvacRepository(getHvacManager());
993 | }
994 |
995 | public static HvacManager getHvacManager() {
996 | return HvacManager.getInstance();
997 | }
998 |
999 | }
1000 |
1001 | ```
1002 |
1003 | ### 构建 Model 层
1004 |
1005 | 在车载应用中 **Model** 层的主要数据源无外乎 有三种**网络数据源**、**HMI本地数据源**、**IPC(进程间通信)数据源**,其中最常见的是只有**IPC数据源,**三种数据源都有的情况往往会出现在主机厂商自行开发的**车载地图应用**中。所以我们这里只考虑如何基于**IPC数据源**构造**Model**层
1006 |
1007 | 定义一个 `XXX``Repository` 继承自 `BaseRepository`,再根据业务需要定义出我们需要使用的接口,这里的`HvacManager`就是**service**提供的用来进行跨进程通信的**IPC-SDK**中的入口。
1008 |
1009 | ```
1010 | public class HvacRepository extends BaseRepository {
1011 |
1012 | private static final String TAG = IpcApp.TAG_HVAC + HvacRepository.class.getSimpleName();
1013 |
1014 | private final HvacManager mHvacManager;
1015 | private HvacCallback mHvacViewModelCallback;
1016 |
1017 | private final IHvacCallback mHvacCallback = new IHvacCallback() {
1018 | @Override
1019 | public void onTemperatureChanged(double temp) {
1020 | if (mHvacViewModelCallback != null) {
1021 | // 处理远程数据,讲他转换为应用中需要的数据格式或内容
1022 | String value = String.valueOf(temp);
1023 | mHvacViewModelCallback.onTemperatureChanged(value);
1024 | }
1025 | }
1026 | };
1027 |
1028 | public HvacRepository(HvacManager hvacManager) {
1029 | mHvacManager = hvacManager;
1030 | mHvacManager.registerCallback(mHvacCallback);
1031 | }
1032 |
1033 | public void clear() {
1034 | mHvacManager.unregisterCallback(mHvacCallback);
1035 | }
1036 |
1037 | public void requestTemperature() {
1038 | LogUtils.logI(TAG, "[requestTemperature]");
1039 | mHvacManager.requestTemperature();
1040 | }
1041 |
1042 | public void setTemperature(int temperature) {
1043 | LogUtils.logI(TAG, "[setTemperature] " + temperature);
1044 | mHvacManager.setTemperature(temperature);
1045 | }
1046 |
1047 | public void setHvacListener(HvacCallback callback) {
1048 | LogUtils.logI(TAG, "[setHvacListener] " + callback);
1049 | mHvacViewModelCallback = callback;
1050 | }
1051 |
1052 | public void removeHvacListener(HvacCallback callback) {
1053 | LogUtils.logI(TAG, "[removeHvacListener] " + callback);
1054 | mHvacViewModelCallback = null;
1055 | }
1056 |
1057 | }
1058 |
1059 | ```
1060 |
1061 | `Repository`通过一个`HvacCallback`将监听的远程数据处理后返回给`ViewModel`。
1062 |
1063 | > 如果应用会与多个不同的模块进行IPC通信,那么建议将这些由不同模块提供的**IPC-SDK**封装在一个Manager中进行统一管理。
1064 |
1065 | ### 构建ViewModel
1066 |
1067 | 在Jetpack中`ViewModel`的用途是封装界面控制器的数据,以使数据在配置更改后仍然存在。在Android的**MVVM** 架构设计中,`ViewModel`是最关键的一层,通过持有`Repository`的引用来进行外部通信
1068 |
1069 | ```
1070 | public class HvacViewModel extends BaseViewModel {
1071 |
1072 | private static final String TAG = IpcApp.TAG_HVAC + HvacViewModel.class.getSimpleName();
1073 |
1074 | private final HvacRepository mRepository;
1075 | // 线程池框架。某些场景,ViewModel访问Repository中的方法可能会需要切换到子线程。
1076 | private final AppExecutors mAppExecutors;
1077 | private MutableLiveData mTempLive;
1078 |
1079 | private final HvacCallback mHvacCallback = new HvacCallback() {
1080 | @Override
1081 | public void onTemperatureChanged(String temp) {
1082 | LogUtils.logI(TAG, "[onTemperatureChanged] " + temp);
1083 | getTempLive().postValue(temp);
1084 | }
1085 | };
1086 |
1087 | public HvacViewModel(HvacRepository repository, AppExecutors executors) {
1088 | super(repository);
1089 | mRepository = repository;
1090 | mAppExecutors = executors;
1091 | mRepository.setHvacListener(mHvacCallback);
1092 | }
1093 |
1094 | @Override
1095 | protected void onCleared() {
1096 | super.onCleared();
1097 | mRepository.removeHvacListener(mHvacCallback);
1098 | mRepository.release();
1099 | }
1100 |
1101 | /**
1102 | * 请求页面数据
1103 | */
1104 | public void requestTemperature() {
1105 | mRepository.requestTemperature();
1106 | }
1107 |
1108 | /**
1109 | * 将温度数据设定到Service中
1110 | *
1111 | * @param view
1112 | */
1113 | public void setTemperature(View view) {
1114 | mRepository.setTemperature(getTempLive().getValue());
1115 | }
1116 |
1117 | public MutableLiveData getTempLive() {
1118 | if (mTempLive == null) {
1119 | mTempLive = new MutableLiveData<>();
1120 | }
1121 | return mTempLive;
1122 | }
1123 | }
1124 |
1125 | ```
1126 |
1127 | ### 构建View层
1128 |
1129 | 最后就是构建View层,一把就是Activity/Fragment和XML。
1130 |
1131 | `HvacActivity`中各个方法含义我们上面封装BaseMvvmActivity的时候已经解释过了,这里不再赘述。
1132 |
1133 | ```
1134 | public class HvacActivity extends BaseMvvmActivity {
1135 |
1136 | private static final String TAG = IpcApp.TAG_HVAC + HvacActivity.class.getSimpleName();
1137 |
1138 | @Override
1139 | protected int getLayoutId() {
1140 | return R.layout.activity_hvac;
1141 | }
1142 |
1143 | @Override
1144 | protected Object getViewModelOrFactory() {
1145 | return AppInjection.getViewModelFactory();
1146 | }
1147 |
1148 | @Override
1149 | protected int getViewModelVariable() {
1150 | return BR.viewModel;
1151 | }
1152 |
1153 | @Override
1154 | protected void initView() {
1155 |
1156 | }
1157 |
1158 | @Override
1159 | protected void initObservable(HvacViewModel viewModel) {
1160 | viewModel.getTempLive().observe(this, new Observer() {
1161 | @Override
1162 | public void onChanged(String temp) {
1163 | LogUtils.logI(TAG, "[onChanged] " + temp);
1164 | }
1165 | });
1166 | }
1167 |
1168 | @Override
1169 | protected void loadData(HvacViewModel viewModel) {
1170 | viewModel.requestTemperature();
1171 | }
1172 | }
1173 |
1174 | ```
1175 |
1176 | ```
1177 |
1178 |
1181 |
1182 |
1183 |
1184 |
1187 |
1188 |
1189 |
1192 |
1193 |
1204 |
1205 |
1214 |
1215 |
1224 |
1225 |
1226 |
1227 |
1228 | ```
1229 |
1230 | 以上就是如何封装一个适合车载应用使用的 **MVVM** 框架。不知道你有没有发现,在HMI中使用AIDL方法。通常是比较麻烦的。我们需要在HMI与Service完成绑定后,我们才能调用Service中实现的Binder方法。但是示例中我们使用的SDK,并没进行绑定操作,而是直接进行调用。关于如何编写基于AIDL的SDK,就放到下一章再介绍,感谢您的阅读。
1231 |
1232 | 本文所涉及的源码请访问:**https://github.com/linux-link/CarMvvmArch**
1233 |
1234 | ## 参考资料
1235 |
1236 | [应用架构指南 | Android 开发者 | Android Developers](https://developer.android.google.cn/jetpack/guide?hl=zh_cn)
--------------------------------------------------------------------------------