Call a class from the MainActivity or Import class from another Android studio project

0

Good!

I have a big mess, I am developing an application which will not be in the market "google play" so I added an AutoUpdate to keep the application up to date, it turns out that the autoupdate I did creating another project (yes, I did not do it directly from the app I'm developing, because I wanted to avoid moving so much code, avoid the delay to compile (I have a coffee maker, so when compiling if it takes xD) and I thought that creating another project for the autoupdate was easier and faster, and once the code was finished, there was only implement / add / import in the main app.) then, this autoupdate in the manifest is like:

 <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And the full MainActivity code

/*
 * Actualizador de Apk sin Market Google Play
 *
 *
 * Confirma la version actual con una remota
 * Muestra los cambios
 * Descarga la nueva apk
 * La ejecuta y ya es parte del usuario instalarla.
 *
 *
 */
public class MainActivity extends AppCompatActivity {

    private static  String url = "localhost/version.json";
    String VersionUpdate;
    String Cambios;
    String link;
    String nombre;
    String ejecutar;

    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

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

    }

    private void permission_check() {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
                return;
            }
        }

        //initialize();
    }

    private class VersionCheck extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(url);
            if (jsonStr != null){
                try {

                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray obtener = jsonObj.getJSONArray("Obtener");
                    for (int i = 0; i < obtener.length(); i++)
                    {
                        JSONObject v = obtener.getJSONObject(i);
                        link = v.getString("link");
                        VersionUpdate = v.getString("version");
                        nombre = v.getString("nombre");
                        Cambios = "";
                        JSONArray cambiosArr = v.getJSONArray("cambios");
                        for (int j = 0; j < cambiosArr.length(); j++) {
                            Cambios += cambiosArr.getString(j) + "\n";
                        }
                    }
                }catch (final JSONException e) {

                    // Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Toast.makeText(getApplicationContext(),
                                    "El formato de JSON es invalido: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "El servidor de comprobar la version esta caido, por favor chequear la version en: Ajustes > Comprobar",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
            return null;
        }

        @Override
        protected void onPostExecute (Void result){

            if (VersionUpdate != null) {

                super.onPostExecute(result);
                String VersionName = BuildConfig.VERSION_NAME;
                if (VersionUpdate.equals(VersionName)) {
                    Toast.makeText(getApplicationContext(),
                            "Version actual: " + VersionName,
                            Toast.LENGTH_LONG)
                            .show();
                } else {

                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Actualización");
                    builder.setIcon(R.mipmap.ic_launcher);
                    builder.setCancelable(false);
                    builder.setMessage("Actual: "+ VersionName + "\n"+ "Disponible: " + VersionUpdate  + "\n" + "\n" + "Incluye: " +"\n" +"\n" + Cambios + "\n")

                            .setPositiveButton("¡Actualizame!", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //Ejecutamos el class para descargar la version
                                    new DownloadFileFromURL().execute(link);

                                }
                            });
                    builder.setNegativeButton("Despues", null);


                    AlertDialog alert = builder.create();
                    alert.show();


                }
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id){
        switch (id){
            case progress_bar_type:
                pDialog = new ProgressDialog(this);
                pDialog.setMessage("Descargando actualización"+"\n"+"Espere...");
                pDialog.setIndeterminate(false);
                pDialog.setMax(100);
                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pDialog.setCancelable(false);
                pDialog.show();
                return pDialog;
            default:
                return null;
        }
    }

    class DownloadFileFromURL extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        @Override
        protected  String doInBackground(String... f_url){
            int count;
            try{
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                int lenghtOfFile = connection.getContentLength();

                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                String fileName = "/download/"+nombre+VersionUpdate+".apk";
                File arch = new File(storageDir+fileName);
                OutputStream output = new FileOutputStream(arch);
                ejecutar = storageDir+fileName;
                byte data[] = new byte[1024];
                long total = 0;

                while((count = input.read(data)) != -1){
                    total += count;

                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    output.write(data, 0, count);
                }
                output.flush();

                output.close();
                input.close();
            }catch (Exception e){
                //Log.e("Error: ", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress){
            pDialog.setProgress(Integer.parseInt(progress[0]));

        }

        @Override
        protected void onPostExecute(String file_url){
            dismissDialog(progress_bar_type);
             //aca ejecutamos al finalizar la descarga
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(ejecutar)),
                    "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            startActivity(intent);
            finish();
        }
    }

}

And in the main app (which is the one I'm developing) I have in the manifest:

<activity
        android:name=".NavigatorActivity"
        android:configChanges="keyboardHidden"
        android:label="XploiT" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEND" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="*/*" />
        </intent-filter>
    </activity>

Now, my question: How to merge, import, add the code "AutoUpdate", to the main application?

I tried to copy and paste the AutoUpdate but I do not know how to call it from NavigatorActivity

    
asked by Luis Rivas 07.05.2018 в 08:43
source

1 answer

0

To import activities from one project to another you simply have to save the project you want to export as a library and then in the project you want to import it by simply adding another library like any other:

  

Project Properties > Android > Add Library

Or I would also take a look at

  

File > Import> Android> Existing Code into Workspace

To add external libraries once exported:

  

File > Project Structure > Dependencies Tab > Add module dependency

And if you refer to the code, it's like any other library:

In the root of your project edit the settings.gradle and add this line

include 'MiApp', ':subProject:NombreDeTuLibreria'

Then clean the project to make sure everything works

gradle clean & build/close the project

and add the following dependency to your build.gradle :

dependencies {
//...
    compile project(':subProject:NombreDeTuLibreria')

}
    
answered by 07.05.2018 в 10:16