Установите apk программно, автоматически обновляя мое приложение - PullRequest
1 голос
/ 08 февраля 2020

Привет, у меня проблемы с этим кодом ... Я хочу проверить на своем сервере, является ли версионный код моего приложения последним, и обновить приложение или нет.

Это моя проверка Активность

'' '

publi c класс CheckUPD расширяет AppCompatActivity {

TextView textServer; // text result from server on layout

int versionCodeThis ;// Version code of this app es. 1
String versionNameThis = ""; // Version name of this app es. V0.01
static String versionCodeServer = "";
static String versionCodeThisString;

static boolean versionegiusta = false;

RequestQueue requestQueue;

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

    textServer = findViewById(R.id.updtxtserver); // text result from server on layout

    requestQueue = Volley.newRequestQueue(this);

    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        versionCodeThis = packageInfo.versionCode; // versionCode of this app es. 1             int
        versionNameThis = packageInfo.versionName; // versionName of this app es. V0.01         String

    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    ((TextView)findViewById(R.id.updtxtcurrent)).setText(getString(R.string.currentver) + " " + versionNameThis);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://google.com/version.json",null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("app");

                        JSONObject app = jsonArray.getJSONObject(0);

                        String name = app.getString("name");
                        String versionName = app.getString("versionName");
                        String versionCode = app.getString("versionCode");

                        textServer.setText(name+ "\n" + versionName + "\n" + versionCode + "\n");

                        versionCodeThisString = String.valueOf(versionCodeThis);     // transform int versionCodeThis in String versionCodeThisString
                        versionCodeServer= versionCode;     // transform int versionCodeThis in String versionCodeThisString

                        if ( versionCodeThisString.equals(versionCode)    ) {
                            Log.i("codiceversioneonline",versionCode);
                            Log.i("codiceversione",versionCodeThisString);
                            Toast.makeText(getBaseContext(), getString(R.string.usinglatest), Toast.LENGTH_SHORT).show();
                            versionegiusta= true;
                        }
                        else  {
                            Toast.makeText(getBaseContext(), getString(R.string.updateavaillable), Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley","ERROR");
                }
            });
    requestQueue.add(jsonObjectRequest);


}

public void download(View view) {
    String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
    String fileName = "latest.apk";
    destination += fileName;
    final Uri uri = Uri.parse("file://" + destination);

    //Delete update file if exists
    File file = new File(destination);
    if (file.exists())
        //file.delete() - test this, I think sometimes it doesnt work
        file.delete();



    //set downloadmanager
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://google.com/latest.apk"));


    //set destination
    request.setDestinationUri(uri);

    // get download service and enqueue file
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request);

    //set BroadcastReceiver to install app when .apk is downloaded
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri,
                    manager.getMimeTypeForDownloadedFile(downloadId));
            startActivity(install);

            unregisterReceiver(this);
            finish();
        }
    };
    //register receiver for when .apk download is compete
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

}

' ''

Все рабочие отлично, за исключением

'' 'publi c void download (Просмотр представления) {String destination = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS) + "/"; String fileName = "latest.apk"; назначение + = имя_файла; final Uri uri = Uri.parse ("file: //" + destination);

    //Delete update file if exists
    File file = new File(destination);
    if (file.exists())
        //file.delete() - test this, I think sometimes it doesnt work
        file.delete();



    //set downloadmanager
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://google.com/latest.apk"));


    //set destination
    request.setDestinationUri(uri);

    // get download service and enqueue file
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request);

    //set BroadcastReceiver to install app when .apk is downloaded
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri,
                    manager.getMimeTypeForDownloadedFile(downloadId));
            startActivity(install);

            unregisterReceiver(this);
            finish();
        }
    };
    //register receiver for when .apk download is compete
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

}

'' '

Загружает последний файл .apk в Папка / download и при попытке установки Показывает «пакет анализа ошибок», но с файловым менеджером symple I go для загрузки и нажатия на latest.apk Будет установлено без проблем. Так как я могу это исправить?

В манифесте уже добавлено разрешение на установку пакета, запись на внешнее и внутреннее хранилище и inte rnet.

Пожалуйста, помогите мне, спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...