Receptor de anuncios
uso de receptores de anuncios (Broadcast Receiver)
Servicios en Android (Receptor de anuncios)
Android fundamentals 07.3: Broadcast receivers
Ejemplo: receptor de anuncios
Ejemplo: Descargar un archivo con un servicio (IntentService) y mostrar una información (o notificación) cuando termine usando un receptor de anuncios
Añadir un switch a la interfaz de usuario para descargar usando DownloadService o DownloadIntentService.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public ActivityMainBinding binding;
private static final int REQUEST_CONNECT = 1;
public static final String WEB = "https://dam.org.es/ficheros/frases.html";
public static final String ACTION_RESP = "RESPUESTA_DESCARGA";
IntentFilter intentFilter;
BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.botonIniciar.setOnClickListener(this);
binding.botonParar.setOnClickListener(this);
intentFilter = new IntentFilter(ACTION_RESP);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
broadcastReceiver = new ReceptorOperacion();
// registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onResume(){
super.onResume();
//---registrar el receptor ---
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onPause(){
super.onPause();
//--- anular el registro del recpetor ---
unregisterReceiver(broadcastReceiver);
}
public class ReceptorOperacion extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String respuesta = intent.getStringExtra("resultado");
binding.salida.setText(respuesta);
// mostrarMensaje(respuesta);
}
}
DownloadIntentService.java
public class DownloadIntentService extends IntentService {
public DownloadIntentService() {
super("DownloadIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String web = intent.getExtras().getString("web");
URL url = null;
try {
url = new URL(web);
descargaOkHTTP(url);
} catch (MalformedURLException e) {
e.printStackTrace();
enviarRespuesta("Error en la URL: " + e.getMessage());
}
}
}
private void descargaOkHTTP(URL web) {
final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(web)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e("Error: ", e.getMessage());
enviarRespuesta("Fallo: " + e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException{
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) {
//throw new IOException("Unexpected code " + response);
Log.e("Error: ", "Unexpected code " + response);
enviarRespuesta("Error: Unexpected code " + response);
} else {
// Read data on the worker thread
final String responseData = response.body().string();
enviarRespuesta("Descarga: fichero descargado OK");
// guardar el fichero descargado en memoria externa
if (escribirExterna(responseData)) {
Log.i("Descarga: ", "fichero descargado");
} else {
Log.e("Error ", "no se ha podido descargar");
}
}
}
}
});
}
private void mostrarMensaje(String mensaje) {
Toast.makeText(this,mensaje, Toast.LENGTH_SHORT).show();
}
private boolean escribirExterna(String cadena) {
File miFichero, tarjeta;
BufferedWriter bw = null;
boolean correcto = false;
try {
tarjeta = Environment.getExternalStorageDirectory();
miFichero = new File(tarjeta.getAbsolutePath(), "frases.html");
bw = new BufferedWriter(new FileWriter(miFichero));
bw.write(cadena);
Log.i("Información: ", miFichero.getAbsolutePath());
enviarRespuesta("Descarga: fichero guardado en\n" + miFichero.getAbsolutePath());
} catch (IOException e) {
if (cadena != null)
Log.e("Error: ", cadena);
Log.e("Error de E/S", e.getMessage());
enviarRespuesta("Error: " + e.getMessage());
} finally {
try {
if (bw != null) {
bw.close();
correcto = true;
}
} catch (IOException e) {
Log.e("Error al cerrar", e.getMessage());
}
}
return correcto;
}
private void enviarRespuesta (String mensaje) {
Intent i = new Intent();
i.setAction(MainActivity.ACTION_RESP);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra("resultado", mensaje);
sendBroadcast(i);
}
}
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.