¿Por qué IntentReceiverLeaked?
Quiero recibir una String
del servidor Bluetooth que es pc Tengo un código java para ello pero cuando ejecuto mi Activity
cliente de Android me muestra esta excepción
Activity com.waseem.mobileclient.bluetoot_app.MainActivity has leaked IntentReceiver com.waseem.mobileclient.bluetoot_app.MainActivity$1@410480f0 that was originally registered here. Are you missing a call to unregisterReceiver()? android.app.IntentReceiverLeaked: Activity com.waseem.mobileclient.bluetoot_app.MainActivity has leaked IntentReceiver com.waseem.mobileclient.bluetoot_app.MainActivity$1@410480f0 that was originally registered here. Are you missing a call to unregisterReceiver()? at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:792) at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:593) at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1111) at android.app.ContextImpl.registerReceiver(ContextImpl.java:1098) at android.app.ContextImpl.registerReceiver(ContextImpl.java:1092) at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:365) at com.waseem.mobileclient.bluetoot_app.MainActivity.onCreate(MainActivity.java:68) at android.app.Activity.performCreate(Activity.java:5008)
Estoy onPause()
registro en onPause()
por qué estoy recibiendo esta excepción por favor ayúdame a cabo Me ha atrapado durante mucho tiempo. aquí está el código del cliente
- NoClassDefFoundError: android.support.v7.internal.view.menu.MenuBuilder
- Appium no puede obtener datos de atributo "content-desc"
- Sugerencias sobre cómo mejorar esta clase simple de agrupación de objetos para Java?
- SDK de Android: ejecuta funciones en segundo plano
- ¿Cuál es el mejor IDE para el desarrollo de java android
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (myBluetoothAdapter == null) { Log.e(TAG, "No Bluetooth Adapter available. Exiting..."); this.finish(); } IntentFilter intent_filter=new IntentFilter(MESSAGE_RECEIVED_INTENT); broad_receiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(MESSAGE_RECEIVED_INTENT)) { showInformation(intent.getExtras().getString("Message"), 5000); getVibrator().vibrate(500); } else { showInformation("Message unable to receive", 5000); getVibrator().vibrate(500); } } }; this.registerReceiver(broad_receiver,intent_filter); Button start_server = (Button)findViewById(R.id.button_start); start_server.setOnClickListener(this); Button stop_server = (Button)findViewById(R.id.button_stop); stop_server.setOnClickListener(this); } @Override protected void onPause() { this.unregisterReceiver(this.broad_receiver); super.onPause(); server.cancel(); restoreBTDeviceName(); } @Override public void onClick(View v) { Button btn = (Button) v; if (btn.getId() == R.id.button_start) { if (!myBluetoothAdapter.getName().startsWith(PREFIX)) myBluetoothAdapter.setName(PREFIX ); if (myBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { requestBTDiscoverable(); server = new AcceptThread(); server.start(); btn.setEnabled(false); ((Button) this.findViewById(R.id.button_stop)).setEnabled(true); } } else if (btn.getId() == R.id.button_stop) { server.cancel(); btn.setEnabled(false); ((Button) this.findViewById(R.id.button_start)).setEnabled(true); restoreBTDeviceName(); } } /** * Launches Discoverable Bluetooth Intent. */ public void requestBTDiscoverable() { Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivityForResult(i, REQUEST); int result = 0; this.onActivityResult(REQUEST, result, i); Log.i(TAG, "Bluetooth discoverability enabled"); } /** * Obtains the Vibrator service. * * @return Vibrator Object. */ private Vibrator getVibrator() { return (Vibrator) getSystemService(VIBRATOR_SERVICE); } /** * Removes the prefix from the device name if the prefix is present. */ private void restoreBTDeviceName() { if (myBluetoothAdapter.getName().startsWith(PREFIX)) myBluetoothAdapter.setName(myBluetoothAdapter.getName().substring(PREFIX.length())); } /** * Shows a information dialog. * * @param message String resource used to define the message. * @param duration Dialog's TTL. */ private void showInformation(String message, long duration) { final Dialog mDialog = new Dialog(this); TextView txt = new TextView(this); txt.setText(message); mDialog.setContentView(txt); mDialog.setTitle("Information"); mDialog.show(); (new Handler()).postDelayed(new Runnable() { public void run() { mDialog.dismiss(); } },duration); // Close dialog after delay } /** * ************************************* AcceptThread ************************************* */ class AcceptThread extends Thread { /** * Tag that will appear in the log. */ private final String ACCEPT_TAG = AcceptThread.class.getName(); /** * The bluetooth server socket. */ private final BluetoothServerSocket mServerSocket; public AcceptThread() { BluetoothServerSocket tmp = null; try { tmp = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(ACCEPT_TAG, UUID.fromString(defaultUUID)); } catch (IOException e) { e.printStackTrace(); } mServerSocket = tmp; } public void run() { BluetoothSocket socket = null; while (true) { try { Log.i(ACCEPT_TAG, "Listening for a connection..."); socket = mServerSocket.accept(); Log.i(ACCEPT_TAG, "Connected to " + socket.getRemoteDevice().getName()); } catch (IOException e) { break; } // If a connection was accepted if (socket != null) { // Do work to manage the connection (in a separate thread) try { // Read the incoming string. String buffer; DataInputStream in = new DataInputStream(socket.getInputStream()); buffer = in.readUTF(); Intent i = new Intent(MESSAGE_RECEIVED_INTENT); i.putExtra("Message", String.format("%sn From: %s", buffer, socket.getRemoteDevice().getName())); getBaseContext().sendBroadcast(i); } catch (IOException e) { Log.e(ACCEPT_TAG, "Error obtaining InputStream from socket"); e.printStackTrace(); } try { mServerSocket.close(); } catch (IOException e) { } break; } } } /** * Will cancel the listening socket, and cause the thread to finish */ public void cancel() { try { mServerSocket.close(); } catch (IOException e) { } } }
- Actualización de la hora y la fecha por segundo en Android
- Cambio de color del texto del botón mediante programación
- Butterknife 8.4.0 no encuentra vistas después de volver a ejecutar la aplicación. Obtiene una excepción NullPointerException
- La URL no se puede emitir a String
- Problema de base de datos SQLite en TextView
- Tratar métodos obsoletos en android
- JSONException: no hay valor para XYZ al intentar getString ("XYZ")
- Android: Error al cargar la imagen en diferentes versiones de Android
La primera línea de LogCat dice:
¿Te has perdido una llamada a unregisterReceiver ()?
Simplemente significa que necesita revisar la documentación de la API de BroadcastReceiver
para obtener ayuda, que dice:
Nota: Si registra un receptor en su implementación de
Activity.onResume()
, debe anular su registro enActivity.onPause()
. (No recibirá intenciones cuando se detiene, y esto reducirá la sobrecarga innecesaria del sistema). No anule el registro enActivity.onSaveInstanceState()
, porque no se llamará si el usuario se mueve de nuevo en la pila de historial.
- Utilizar NDK en Android Studio (OpenCV)
- android DialogFragment android: onClick = "buttonCancel" causas IllegalStateException no pudo encontrar un método