日常開發中我總希望Gradle裏面配置一下,我們的java代碼就會自動修改邏輯,簡稱一勞永逸
這麼說來很抽象,我舉幾個例子大家就明白了
- gradle文件中設置不使用flutter,java代碼就會自動使用Native頁面
- gradle文件中設置使用flutter,java代碼就會自動使用Flutter頁面
實現思路
gradle修改之後將變動寫入android的assets文件夾下面,android代碼運行的時候再讀取assets裏面的文件
把項目地址奉上:
關鍵代碼瀏覽:
test.gradle
def targetFile = new File("./app/src/main/assets/test.txt")
//這裏獲取的實際是Java中的BufferedOutputStream
targetFile.withOutputStream { osm ->
String result = isUseFlutter
osm.write(("使用Flutter頁面?" + result).getBytes())
}
Settings.gradle
rootProject.name='test'
include ':app'
apply from: 'test.gradle'
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AppCompatTextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.tv);
}
public void readFile(View view) {
InputStream is = null;
String msg = null;
try {
is = this.getResources().getAssets().open("test.txt");
byte[] bytes = new byte[is.available()];
is.read(bytes);
msg = new String(bytes);
mTextView.setText(msg);
} catch (IOException e) {
e.printStackTrace();
mTextView.setText("代碼出錯啦! "+e.getMessage());
}
}
}
附上兩篇博客: