Gradle的一個奇淫巧技

日常開發中我總希望Gradle裏面配置一下,我們的java代碼就會自動修改邏輯,簡稱一勞永逸

這麼說來很抽象,我舉幾個例子大家就明白了

  1. gradle文件中設置不使用flutter,java代碼就會自動使用Native頁面
  2. gradle文件中設置使用flutter,java代碼就會自動使用Flutter頁面

實現思路

gradle修改之後將變動寫入android的assets文件夾下面,android代碼運行的時候再讀取assets裏面的文件

把項目地址奉上:

GradleJavaTest Demo

關鍵代碼瀏覽:

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());
        }
    }
}

在這裏插入圖片描述

附上兩篇博客:

任玉剛Gradle博客

Gradle文件讀寫操作

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章