Bluetooth Verbindung bricht immer nach 489 erfolgreichen Verbindungen ab

  • 6 Antworten
  • Letztes Antwortdatum
C

Comes

Neues Mitglied
0
Auf meinem PC läuft eine Test Java-Applikation, die mit Hilfe der
BlueCove Bibliothek eine SPP-Verbindung zu meinem Nexus 4 aufbaut.
Die Apllikation sendet 72 Bytes ans Android Handy und wartet auf eine Antwort. Wenn die Antwort gekommen ist wartet das Programm 3 Sekunden und sendet erneut 72 Bytes.

Auf dem Nexus läuft im Hintergrund ein Bluetooth Listener der beim Booten startet. Die Applikation basiert auf dem BluetoothChat Beispiel. Wenn Daten am Gerät ankommen überprüft er diese und sendet eine Antwort zurück.

Das funktioniert alles ganz gut. Aber nach 489 Verbindungen bricht die Android Seite ab während die PC-Seite weiterläuft.
Es kommt zu folgendem Fehler:
Code:
getBluetoothService() called with no BluetoothManagerCallback 
Shutting down VM 
threadid=1: thread exiting with uncaught exception (group=0x41b34ba8)
FATAL EXCEPTION: main 
Process: de.tum.lme.diamantum:remote_blue, PID: 21567
java.lang.NullPointerException: FileDescriptor must not be null   
    at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:174)     
    at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:905)     
    at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:897)     
    at android.bluetooth.IBluetooth$Stub$Proxy.createSocketChannel(IBluetooth.java:1355)      
    at android.bluetooth.BluetoothSocket.bindListen(BluetoothSocket.java:349)     
    at android.bluetooth.BluetoothAdapter.createNewRfcommSocketAndRecord(BluetoothAdapter.java:1055)     
    at android.bluetooth.BluetoothAdapter.listenUsingRfcommWithServiceRecord(BluetoothAdapter.java:976)     
    at com.test.btconn.BluetoothHandling$AcceptThread.<init>(BluetoothHandling.java:449)     
    at com.test.btconn.BluetoothHandling.start(BluetoothHandling.java:216)     
    at com.test.btconn.BluetoothListenerService.setupBtSockets(BluetoothListenerService.java:330)     
    at com.test.btconn.BluetoothListenerService.manageBtState(BluetoothListenerService.java:249)     
    at com.test.btconn.BluetoothListenerService.setBtStateDisconnected(BluetoothListenerService.java:383)     
    at com.test.btconn.BluetoothListenerService.access$5(BluetoothListenerService.java:378)     
    at com.test.btconn.BluetoothListenerService$2.handleMessage(BluetoothListenerService.java:421)
Die App hat wohl ein Problem mit dem ParcelFileDescriptor, der plötzlich Null ist. Aber warum?

Das Problem tritt auch jedesmal auf, wenn die Pausenzeit zwischen den Verbindungen geändert wird oder die Datenmenge variiert. Auf dem Gerät läuft Android 4.4.2.

Ach ja, nach jeder Verbindung schließe ich den BluetoothServerSocket.

Ich hoffe jemand kennt sich mit dem Bluetooth Chat aus und kann mir weiterhelfen. Danke schonmal
 
Wenn ich Deine Fehlermeldung richtig interpretiere, arbeitest du mit einem RemoteService. Das heißt, du hast mindestens 2 Prozesse (Diese können auf verschieden Kerne laufen). Kommunikation zwischen ist ein Thema für sich. Am Besten du benutzt BoardcastReceiver für deine Kommunikation.

Mehr kann ich nicht sagen, da ich Dein Code nicht kenne. Ich hoffe, du hast nicht die Konstanten MODE_WORLD_READABLE ParcelFileDescriptor | Android Developers oder MODE_WORLD_WRITEABLE ParcelFileDescriptor | Android Developers gesetzt. Diese sind fehlerbehaftet.
 
Sorry für die späte Antwort, war grad unterwegs.
Woraus erkennst du, dass hier zwei Prozesse laufen?

Ich habe mal versucht, ein "Minimal"-Programm zu machen, was leider gar nicht so einfach ist. Aber ich führe es unten an.

Das Problem bleibt weiterhin: Ich sende alle 3 Sekunden Daten über Bluetooth an mein Smartphone und nach 489 Übertragungen erhalte ich folgende Fehlermeldung:
Code:
05-15 12:36:53.015: E/AndroidRuntime(28685): FATAL EXCEPTION: main
05-15 12:36:53.015: E/AndroidRuntime(28685): Process: com.example.bluetoothtest:remote_blue, PID: 28685
05-15 12:36:53.015: E/AndroidRuntime(28685): java.lang.NullPointerException: FileDescriptor must not be null
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:174)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:905)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:897)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.bluetooth.IBluetooth$Stub$Proxy.createSocketChannel(IBluetooth.java:1355)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.bluetooth.BluetoothSocket.bindListen(BluetoothSocket.java:349)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.bluetooth.BluetoothAdapter.createNewRfcommSocketAndRecord(BluetoothAdapter.java:1055)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.bluetooth.BluetoothAdapter.listenUsingRfcommWithServiceRecord(BluetoothAdapter.java:976)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothHandling$AcceptThread.<init>(BluetoothHandling.java:293)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothHandling.start(BluetoothHandling.java:75)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothListenerService.setupBtSockets(BluetoothListenerService.java:223)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothListenerService.manageBtState(BluetoothListenerService.java:168)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothListenerService.setBtStateDisconnected(BluetoothListenerService.java:320)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothListenerService.access$6(BluetoothListenerService.java:315)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.example.bluetoothtest.BluetoothListenerService$2.handleMessage(BluetoothListenerService.java:262)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.os.Looper.loop(Looper.java:136)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at java.lang.reflect.Method.invokeNative(Native Method)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at java.lang.reflect.Method.invoke(Method.java:515)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 12:36:53.015: E/AndroidRuntime(28685): 	at dalvik.system.NativeStart.main(Native Method)

Der Android-Code sieht wie folgt aus:
BootReceiver.java
Code:
public class BootReceiver extends BroadcastReceiver {
	Context c;	
	@Override
	public void onReceive(final Context context, Intent intent) {

		Intent blueService = new Intent(BluetoothListenerService.class.getName());
		blueService.putExtra("callerId", "BootReceiver");
		if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
			Log.d(TAG, "Stopped Service");
		}
		
		if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {			
			context.startService(blueService);
		}
	}
}

BluetoothListenerService.java

Code:
public class BluetoothListenerService extends Service {
		
	private static final String TAG = BluetoothListenerService.class.getSimpleName();
	
	private BluetoothAdapter mBtAdapter;
	private BluetoothHandling mBluetoothHandling;
	private PowerManager.WakeLock wl;
	private PowerManager pm;	
	private ByteArrayOutputStream mPacket;
	private StringBuilder btTest;	
	private static final int STATE_CONNECTED = 0x01;
	private static final int STATE_DISCONNECTED = 0x02;	
	private int mConnectionState;	
	private boolean mPDU_valid = true;	
	private String mConnectedDeviceName;
	private String mConnectedDeviceMac;	
	private MemoryInfo mi;
	private ActivityManager activityManager;
	
	
	
	@Override
	public void onCreate() { //
		
		if(android.os.Build.VERSION.SDK_INT > 9){
			StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().build();
			StrictMode.setThreadPolicy(policy);
		}
		super.onCreate();
		
		// Log a Hello here I am!
		Log("started");
		mPacket = new ByteArrayOutputStream(128);
		
		// get a handle to the BT Interface
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		
		// check if the system supports BT
		if (mBtAdapter == null) {
			Log.e(TAG, getString(com.example.comesbluetoothtest.R.string.ERROR_NO_BT_SUPPORT));
			Toast.makeText(getApplicationContext(), getString(com.example.comesbluetoothtest.R.string.ERROR_NO_BT_SUPPORT), Toast.LENGTH_LONG).show();
			stopSelf();
		}
		
		// start Bluetooth state handling. From this point till stopBt() is called, service will make sure that bluetooth is running.
		startBtManager();
		
		// prevent deep sleep by wake lock in order to receive bluetooth data (there is a error with bluetoothListener during deep sleep
		preventDeepSleep();
		wakeLockAcquire();		
		
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log("restart service");
		super.onStartCommand(intent, flags, startId);
		return START_STICKY;
	}
	
	@Override
	public void onDestroy() {
		Log("bin in blservice onDestroy");
	}
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	
	/**
	 * Starts the bluetooth state handling. Installs broadcast listners and enters the state manager.
	 * This method will ensure, that bt is running and discoverable till stopBtManager() is called.
	 */
	private void startBtManager() { //
		
		// setup listeners to monitor changes to BT state
		installBtBroadcastListeners();
		
		// set connection state to disconnected
		mConnectionState = STATE_DISCONNECTED;
		
		// enter manageBtState()
		manageBtState();
	}
	
	
	/**
	 * Class to catch changes in bluetooth state. Will listen for ACTION_STATE_CHANGED and ACTION_SCAN_MODE_CHANGED and
	 * enter manageBtState after broadcast received to act to the new state.
	 */
	private BroadcastReceiver mBtBroadcastReceiver = new BroadcastReceiver() { //
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Log("onReceive() with " + intent.getAction());
			if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED) || 
				intent.getAction().equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
				
				manageBtState();
			}
		}
	};
	
	
	/**
	 * Install broadcast receivers that will be triggered on changes in bluetooth state.
	 */
	private void installBtBroadcastListeners() { //

		registerReceiver(mBtBroadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
		registerReceiver(mBtBroadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
	}
	
	
	
	/**
	 * Entry point of Bluetooth state handling.
	 * This method will ensure, that bluetooth is running and discoverable all the time.
	 */
	private void manageBtState() { //
		
		int state = mBtAdapter.getState();
		Log("manageBtState " + state);
		
		switch(state) {
		case BluetoothAdapter.STATE_OFF:
			switchOnBluetooth();
			break;
		case BluetoothAdapter.STATE_TURNING_OFF:
			stopBluetoothConnections();
			break;
		case BluetoothAdapter.STATE_ON:
			setupBtSockets();
			// we don't need to be discoverable for a connection
//			manageBtScanmode();
			break;
		case BluetoothAdapter.STATE_TURNING_ON:
		default:
			break;
		}
	}
	
	
	/**
	 * Switch on Bluetooth.
	 */
	private void switchOnBluetooth() { //
		Log("switchOnBluetooth()");
		Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		enableBt.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(enableBt);
	}
	
	
	/**
	 * Stop all open BluetoothConnections
	 */
	private void stopBluetoothConnections() { //
		Log("stopBluetoothConnections()");

		if (mBluetoothHandling != null) {
			mBluetoothHandling.stop();
			mBluetoothHandling = null;
		}
		Log("mBluetoothHandling: " + mBluetoothHandling);
	}
	
	
	/**
	 * open the Bluetooth Sockets for connection.
	 */
	private void setupBtSockets() { //
		
		Log("setupBtSockets");		
		getRunningServices();
		
		if(mBtAdapter != null){
			Log("set BTAdapter to null; current state: " + mBtAdapter.getState());	
			mBtAdapter = null;
			mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		}
		
		if (mBluetoothHandling != null) {
			mBluetoothHandling.stop();
			mBluetoothHandling = null;
		}
		mBluetoothHandling = new BluetoothHandling(this, mHandler,mBtAdapter);
		mBluetoothHandling.start();
		
		Log("run Garbage Collector");
		System.gc();
		
		Log("CPU check: " + readUsage());		
		
		activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		mi = new MemoryInfo();
		activityManager.getMemoryInfo(mi);
		long availableMegs = mi.availMem / 1048576L;
		Log("get Memory: " + availableMegs);
	}
	
	
	
    /**
     * Handler managing communication with bluetooth interface.
     */
    private Handler mHandler = new Handler() { //
        @Override
        public void handleMessage(Message msg) {
        	Log.d(TAG, "mHandler -> BluetoothHandling from state: " + msg.what);
            switch (msg.what) {
            
            // State change
            case BluetoothHandling.MESSAGE_STATE_CHANGE:
            	Log.d(TAG, "mHandler -> BluetoothHandling to state: " + msg.arg1);
                switch (msg.arg1) {                
                case BluetoothHandling.STATE_CONNECTED:
                	setBtStateConnected();
                	Log("State: connected");
                	mPDU_valid = true; //TODO: TOM AND
                    break;
                case BluetoothHandling.STATE_CONNECTING:
                	Log("State: connecting");
                    break;
                case BluetoothHandling.STATE_LISTEN:
                	Log("State: listening");
                	if (getBtState() == STATE_CONNECTED) setBtStateDisconnected();
                	break;
                case BluetoothHandling.STATE_NONE:
                	if (getBtState() == STATE_CONNECTED){
                		Log("State connected");
                		setBtStateDisconnected();
                	}
                	Log("State: not connected");
                    break;
                }
                break;
                
            // Send a message via bt
            case BluetoothHandling.MESSAGE_WRITE:
                break;
           
            // received a message via bt
            case BluetoothHandling.MESSAGE_READ:
            	if (mPDU_valid)
                	processInput(msg.arg1, (byte[]) msg.obj);
                break;
                
            // received device name
            case BluetoothHandling.MESSAGE_DEVICE_NAME:
                // save the connected device's name
            	mConnectedDeviceName = msg.getData().getString(BluetoothHandling.DEVICE_NAME);
            	mConnectedDeviceMac  = msg.getData().getString(BluetoothHandling.DEVICE_MAC);
            	Log("connected to device: " + mConnectedDeviceName + " with mac: " + mConnectedDeviceMac);
                break;
                
            // receive a buffer from an HMM Device
            case BluetoothHandling.MESSAGE_RECEIVED_BUFFER:
            	mConnectedDeviceMac = msg.getData().getString(BluetoothHandling.DEVICE_MAC);
            	mConnectedDeviceName = msg.getData().getString(BluetoothHandling.DEVICE_NAME);
            	break;
                
            // received a toast to show
            case BluetoothHandling.MESSAGE_TOAST:
                break;
            }
        }
    };	
	
    private void setBtStateConnected() { //
		mConnectionState = STATE_CONNECTED; 
	}
	
    
    private int getBtState() { //
		return mConnectionState;
	}
    
    
    private void setBtStateDisconnected() { //
		Log("setBtStateDisconnected");
		mConnectionState = STATE_DISCONNECTED;
		mConnectedDeviceMac="empty";
		mConnectedDeviceName="empty";
		manageBtState();
	}
	
	
    private void processInput(int len, byte[] rxpacket) {
    	
    	mPacket.write(rxpacket, 0, len);
    	Log.d(TAG, "< Incoming Data "+getHex(rxpacket, len));
    }
    
    static final String HEXES = "0123456789ABCDEF";
    
    public static String getHex( byte [] raw, int len ) {
      if ( raw == null ) {
        return null;
      }
      final StringBuilder hex = new StringBuilder( 3 * raw.length );
      for ( final byte b : raw ) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4))
           .append(HEXES.charAt((b & 0x0F)))
           .append(" ");
        if (--len == 0)
        	break;
      }
      return hex.toString();
    }

und schließlich BluetoothHandling
Code:
public class BluetoothHandling {
	
	private final Handler mHandler;
	private BluetoothAdapter mAdapter;    
	
    private ConnectedThread mConnectedThread;
    private AcceptThread mAcceptThread;
    private BluetoothSocket socket;
    
    
    private static final UUID MY_UUID_AND = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");    
    
    
	public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int MESSAGE_RECEIVED_BUFFER = 6;
    
    public static final int STATE_NONE = 0;
    public static final int STATE_LISTEN = 1;
    public static final int STATE_CONNECTING = 2;
    public static final int STATE_CONNECTED = 3;
    private int mState;
    
    private static final String TAG = BluetoothHandling.class.getSimpleName();
    private static final String NAME = "abcdefg";
    
    public static final String DEVICE_NAME = "device_name";
    public static final String DEVICE_MAC = "device_mac";
    public static final String BUFFER = "the_buffer";
    public static final String LENGTH = "the_number_of_bytes";
    public static final String MODE = "a_mode";
    public static final String TOAST = "toast";
    
    
	
	
    public BluetoothHandling(Context context, Handler handler, BluetoothAdapter mAdapter2) {
    	Log("constructor");
    	mAdapter = mAdapter2;
        mState = STATE_NONE;
        mHandler = handler;
    }
	
	
    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start() {
        Log("start");

        // Cancel any thread currently running a connection
        stop();

        // Start the thread to listen on a BluetoothServerSocket
        if (mAcceptThread == null) {
        	mAcceptThread = new AcceptThread();
        	mAcceptThread.start();
        }
        setState(STATE_LISTEN);
    }
	
    
    /**
     * Stop all threads
     */
    public synchronized void stop() {
        Log("stop method: cancel Threads and socket");
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
        
        if (socket != null) {
        	Log.d(TAG, "close BluetoothSocket socket: " + socket.isConnected());
        	try {
        		socket.getInputStream().close();
        		socket.getOutputStream().close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }        
        setState(STATE_NONE);
    }
    
    
    
    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        Log("setState() " + mState + " -> " + state);
        mState = state;
        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }
    
    
    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
    	Log("Device connection was lost");    	
        setState(STATE_LISTEN);
    }
    
    
    
    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        Log("in void connected mit device " + device.getAddress());

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();       

        setState(STATE_CONNECTED);
    }
    
	
    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }
	
	
    private void Log(String string){
    	Log.d(TAG, string);
    }
    
    
    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {

        private InputStream mmInStream;
        private OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            Log("create ConnectedThread");
            mmInStream = null;
            mmOutStream = null;

            // Get the BluetoothSocket input and output streams
            try {
            	mmInStream = socket.getInputStream();
            	mmOutStream = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }
        }

        public void run() {
            Log("BEGIN mConnectedThread");
            byte[] buffer = new byte[128];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                    
                    // we need to flush the buffer, otherwise we get wrong data
                    buffer = null;
                    buffer = new byte[128];
                } catch (IOException e) {
                	// we don't need the error log, this is expected behaviour
                	Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
            Log("finished run method within mConnectedThread");
        }

        /**
         * Write to the connected OutStream.
         * @param buffer  The bytes to write
         */
        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);

                // Share the sent message back to the UI Activity
                mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
        	
        	Log("cancel ConnectedThread");
        	
        	if (mmInStream != null) {
        		try {
        			Log("close mmInStrem");
					mmInStream.close();
				} catch (IOException e) {
	                Log.e(TAG, "close() of input stream failed", e);
				}
				mmInStream = null;
        	}
        	
        	if (mmOutStream != null) {
        		try {
        			Log("close mmOutStream");
					mmOutStream.close();
				} catch (IOException e) {
	                Log.e(TAG, "close() of output stream failed", e);
				}
				mmOutStream = null;
        	}
        	
        	if (socket != null)  {
        		try {
        			Log("close socket in mConnectedThread");
        			socket.getInputStream().close();
        			socket.getOutputStream().close();
        			socket.close();
        		} catch (IOException e) {
        			Log.e(TAG, "close() of connect socket failed", e);
        		}
        		socket = null;
        	}
        }
    }
    
    /**
     * This thread runs while listening for incoming connections. It behaves
     * like a server-side client. It runs until a connection is accepted
     * (or until cancelled).
     */
    private class AcceptThread extends Thread {
        // The local server socket
        private BluetoothServerSocket mmServerSocket; 

        public AcceptThread() {
        	Log("bin in AcceptThread");
            // Create a new listening server socket
            try {
            	Log("create mAdapter");
            	
            	/////////////////////////////////////////
            	////////////////////////////////////////
            	     /////////// ERROR //////////
            	////////////////////////////////////////
            	////////////////////////////////////////
            	//TODO: nach 489 Übertragungen kackt das Programm hier ab
            	mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID_AND);
            } catch (IOException e) {
                Log("listen() failed: " + e.getMessage());
            }
        }

        public void run() {
            Log("BEGIN mAcceptThread " + this);
            setName("AcceptThread");
            socket = null;

            // Listen to the server socket if we're not connected
            while (mState != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Log("accept() failed: " + e.getMessage());
                    break;
                }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (BluetoothHandling.this) {
                    	
                    	Log("State in AcceptThread " + mState);
                        switch (mState) {                        
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            // Situation normal. Start the connected thread.
                        	Log("Accept Thread connected");
                            connected(socket, socket.getRemoteDevice());
                            try {
								mmServerSocket.close();
							} catch (IOException e1) {
								Log("mmServerSocket close refused");
								e1.printStackTrace();
							}
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Either not ready or already connected. Terminate new socket.
                            try {
                            	Log("STATE_CONNECTED: is socket connected? " + socket.isConnected());
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            Log("END mAcceptThread");
        }

        public void cancel() {
            Log("cancel AcceptThread by closing BluetoothServerSocket (not BluetoothSocket) " + this.getName());
            try {
            	socket = null;
            	if(mmServerSocket != null)
            		mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of server failed", e);
            }
        }
    }
    
}

Kann mir irgendjemand helfen?

Danke und Grüße
 
Hi,

da ich auch gerne mit Bluetooth herumexperementiere, würde ich dir gerne helfen.
Meinst du, du könntest mir beide Programme (PC und Handheld) als Eclipse/Andoid Studio Projekt exportieren, so dass ich genau deinen Fehler reproduzieren kann?

Ich würde dann mit dem Trace debuggen und versuchen etwas zu finden.
 
Antwort auf deine Frage:

Code:
Process: de.tum.lme.diamantum:remote_blue, PID: 21567
Das ist ein Remote Service. Remote Service laufen in einem eigenen Prozess.


Das Problem liegt an deinen Menge der Bluetooth -Verbindungen. Soweit ich weiß, kann man 7 aktive und insgesamt 248 Verbindungen (sleeping) aufbauen. Deine Verbindungen werden nicht beendet. Bei 249 Verbindung kommt es dann zum Crash. Dein Device kann kein weitere Verbindung unterhalten, und liefert jetzt ein null-Objekt zurück. Welches dann den Fehler liefert.

Ich habe mir den Code jetzt explizit angeschaut, aber ich denke du solltest pro Verbindung nur ein Thread benutzen. Oder dich in das Thema mal richtig einarbeiten.
 
Hi,

danke für eure Antworten.

@Kardroid: anbei die zwei eclipse dateien; bin gespannt, was du herausfindest...

@markus.tullius: ich dachte, dass ich jede Verbindung wieder ordnungsgemäß schließe; habe mich schließlich auch an das Beispiel BluetoothChat gehalten. Ich befolge mal deinen Rat und mache nur einen Thread. Bin gespannt, ob das funktioniert. Ich melde mich ...
 

Anhänge

  • BluetoothTest.7z
    634 KB · Aufrufe: 103
  • BT_client.7z
    525,7 KB · Aufrufe: 121
Hallo Comes,

ich habe beide Projekte runtergeladen und auch kompiliert bekommen, leider kann ich den Client nicht starten, da die bluetooth-Jar nicht mehr auf Mavericks läuft.

Mein Windowslaptop hat leider kein Bluetooth, aber ich versuche in den nächsten Tagen mal meinen Windows-StandPC.
 
Zurück
Oben Unten