Android: detecta cuando la aplicación está instalada
Estoy intentando descargar una aplicación de Android desde un servidor utilizando la clase DownloadManager
, instalarla y luego detectar cuándo se completa la instalación. Estoy utilizando dos receptores: uno para detectar el proceso de descarga y el otro para detectar el proceso de instalación. El primer receptor funciona correctamente, pero el segundo no. ¿Que estoy haciendo mal?
DownloadManager dm = (DownloadManager) DownloadApplicationActivity.this.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request req = new DownloadManager.Request(Uri.parse(MY_LINK)); req.setTitle(MY_TITLE) .setDescription("Downloading ....") // download the package to the /sdcard/downlaod path. .setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, MY_PATH); long enqueue = dm.enqueue(req); BroadcastReceiver receiver= new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { Query query = new Query(); query.setFilterById(enqueue); Cursor c =dm.query(query); if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { // show a notification bar. NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon,"",System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_NO_CLEAR; Intent i = new Intent(Intent.ACTION_VIEW); // when the notification is clicked, install the app. i.setDataAndType(Uri.fromFile(new File(Environment .getExternalStorageDirectory() + APP_PATH)),"application/vnd.android.package-archive"); PendingIntent pendingIntent = PendingIntent.getActivity( activity, 0, i, 0); notification.setLatestEventInfo(activity, MY_TEXT, MY_TEXT,pendingIntent); notification.number += 1; notificationManager.notify( 0, notification); //i want to detect the app's installation, I register a ne receiver registerReceiver(installReceiver,new IntentFilter(Intent.ACTION_PACKAGE_ADDED)); } } }; BroadcastReceiver installReceiver= new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { Uri data = intent.getData(); String packageName = data.getEncodedSchemeSpecificPart(); Log.i("The installed package is: ", "" + packageName); } } };
- ¿Utilizar un receptor de difusión para iniciar AlarmManager en Android?
- BroadcastReceiver SMS_Received no funciona en nuevos dispositivos
- AlarmManager: cómo programar una alarma diaria y hacer frente a cambios de tiempo
- AlertDialog de dentro de BroadcastReceiver ?? Se puede hacer?
- No se puede instanciar el receptor, java.lang.IllegalAccessException: acceso a la clase no permitido
- DownloadManager.ACTION_DOWNLOAD_COMPLETE Receptor de difusión que recibe el mismo ID de descarga más de una vez con diferentes estados de descarga en Android
- ¿Dónde debo usar Servicio, AsyncTask y Broadcast Receiver?
- BroadcastReceiver intentando devolver el resultado durante una transmisión no ordenada - PACKAGE_ADDED en Android
- Android - ¿Cómo obtener una vista desde el contexto?
- Recibir la misma intención difundió varias veces pero sólo envió una vez
- ¿Cómo enviar datos a través de PendingIntent a Broadcast?
- ¿Es posible definir un receptor de difusión como una clase interna en el archivo de manifiesto?
- Registro de Receptor de Difusión en Manifiesto vs. Actividad
Resolví mi problema, agregué
IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED); intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL); intentFilter.addDataScheme("package");
antes de la línea:
registerReceiver(installReceiver, intentFilter);
Puedes probar el código de abajo. De esta manera puede obtener todas las actividades que pueden ser llamadas por una intención y si conoce el nombre de la actividad y está presente en la lista recuperada por queryIntentActivities()
.. usted sabe que está instalado.
public void callQrScan() { Intent intent1 = new Intent("com.google.zxing.client.android.SCAN"); if(isCallable(intent1)== true){ Context context = getApplicationContext(); CharSequence text = "Scan Niet Gelukt"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else{ Context context = getApplicationContext(); CharSequence text = "Scan Niet Gelukt"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } Button tempbutton = (Button)findViewById(R.id.Button03); tempbutton.setOnClickListener(new OnClickListener() { public void onClick(final View v) { callQrScan(); } }); } private boolean isCallable(Intent intent1) { List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent1, PackageManager.MATCH_DEFAULT_ONLY); if(list.size() > 0) return true ; else return false; }
Espero eso ayude 🙂
- ¿Cuál es la diferencia entre los campos android y android2 en los archivos .xml?
- ¿Para qué sirve el "fragmento que proporciona el contexto" del editor gráfico de diseño gráfico?