» »

[Android] Bluetooth aplikacija

[Android] Bluetooth aplikacija

marjan_h ::

Pozdravljeni,

napisal sem aplikacijo s pomočjo android guide

pa mi crasha vedno ko jo poženem, in ne vidim napake. Prosil bi če kdo ki piše te aplikacije strokovno pogleda kodo.

public class StartActivity extends Activity{
 
    ArrayAdapter<String> listAdapter;
    ListView listView;
    BluetoothAdapter btAdapter;
    Set<BluetoothDevice> devicesArray;
    IntentFilter filter;
    ArrayList<String> pairedDevices;
    ArrayList<BluetoothDevice> devices;
    Button bu;
    public static final UUID MY_UUID = UUID.fromString("94A04430-0B83-11E4-9191-0800200C9A66");
    
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                pairedDevices.add(device.getName());
            }
        }
    };

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        
        // inicializacija
        init();
        
        if(btAdapter==null){
            Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
            finish();
        }
        else{
            if(!btAdapter.isEnabled()){
                turnOnBT();
            }
            
            getPairedDevices();
            startDiscovery();
        }
 
 
    }
    private void startDiscovery() {
    	
        btAdapter.cancelDiscovery();
        btAdapter.startDiscovery();
        
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        
        listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,pairedDevices);
        listView.setAdapter(listAdapter);
         
    }
    private void turnOnBT() {
    	
        Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, 1);
    }
    private void getPairedDevices() {
    	
        devicesArray = btAdapter.getBondedDevices();
        if(devicesArray.size()>0){
            for(BluetoothDevice device:devicesArray){
                pairedDevices.add(device.getName());
                 
            }
        }
        listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,pairedDevices);
        listView.setAdapter(listAdapter);
        
    }
    private void init() {
    	
        listView=(ListView)findViewById(R.id.listView1);
        bu = (Button)findViewById(R.id.go);
        
        bu.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
            	try{
   		         Intent i = new Intent(getApplicationContext(), Graph.class);
   		         startActivity(i);
   		    	}
   		    	catch(Exception e){e.printStackTrace();}
            }
        });
        

        listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        		BluetoothDevice selectedDevice = devices.get(position);
        		
        		ConnectThread connect = new ConnectThread(selectedDevice);
                connect.start();
        	}
        	
        	 });
        
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        
        pairedDevices = new ArrayList<String>();
        devices = new ArrayList<BluetoothDevice>();
        
    }
    
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
     
        public ConnectThread(BluetoothDevice device) {

            BluetoothSocket tmp = null;
            mmDevice = device;
     
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) { }
            mmSocket = tmp;
        }
     
        public void run() {
        	
            btAdapter.cancelDiscovery();
     
            try {

                mmSocket.connect();
            } catch (IOException connectException) {

                try {
                    mmSocket.close();
                } catch (IOException closeException) { }
                return;
            }
            // klici Connected thread, zakljucek
            ConnectedThread objekt = new ConnectedThread(mmSocket);
        }
     
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
    
    private class ConnectedThread extends Thread {
    	
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
     
        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
     
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }
     
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
     
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes; 
            
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);
                    String str = new String(buffer, "UTF-8");
                    // prikazi tekst
                    Toast.makeText(getApplicationContext(), str, 0).show();
                } catch (IOException e) {
                    break;
                }
            }
        }
     
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
}


Hvala za pomoč, UUID sem dobil z spletnim generatorjem. Cilj aplikacije je da prikaže tekst ki mu je bil poslan.

Mavrik ::

Joj, ti resno misliš da bo šao kdo pregledovat 200 vrstic kode in jo probavat... ko se tebi ni dalo niti loga prilepiti zraven?
The truth is rarely pure and never simple.

marjan_h ::

log izpiše success. Problem nastane ko naložim aplikacijo na mobitel.

Oprostite ker je dolga koda, vendar je veliko skopirano z uradne strani tako da nekdo ki je že to programiral bi moral hitro opaziti kakšno napako.

Hvala.

Mavrik ::

In... loga s telefona vseeno ne bi prilepil?
The truth is rarely pure and never simple.

marjan_h ::

Zanimivo, da danes pa se ne sesuje. Mogoče se sesuje samo takrat ko se mora povezati z oddaljeno napravo. Prejeti tekst pa ne deluje. Na strani pošiljatelja je vse vredu sem preveril.

Nisem tudi vedel da se da log iz telefona dobiti.

2014-07-15 09:09:16.910 2 3840/InputMethodManager: onWindowFocus: android.widget.ListView{414c74c8 VFED.VCL .F....ID 0,72-480,744 #7f04002a app:id/lsLog} softInputMode=272 first=true flags=#1810100
2014-07-15 09:09:16.910 2 3840/InputMethodManager: START INPUT: android.widget.ListView{414c74c8 VFED.VCL .F....ID 0,72-480,744 #7f04002a app:id/lsLog} ic=null tba=android.view.inputmethod.EditorInfo@417bffb8 controlFlags=#105
2014-07-15 09:09:16.912 2 3840/InputMethodManager: Starting input: Bind result=InputBindResult{com.android.internal.view.IInputMethodSession$Stub$Proxy@41855d68 com.cootek.smartinputv5/.TouchPalIME #63}


Lahko sedaj nekdo pogleda kodo? Tam kjer piše prikaži tekst bi moral prikazati prejeti tekst.

Najlepša hvala za pomoč.

marjan_h ::

Opazil sem da sedaj samo ko pritisnem na dotično napravo v listview mi crasha.

listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        		BluetoothDevice selectedDevice = devices.get(position);
        		
        		ConnectThread connect = new ConnectThread(selectedDevice);
                connect.start();
        	}
        	
        	 });


Je to pravilno s strani listview sprogramirano?

Sry za double post. Hvala za pomoč.


Vredno ogleda ...

TemaSporočilaOglediZadnje sporočilo
TemaSporočilaOglediZadnje sporočilo
»

C#, OBD2 in branje iz porta

Oddelek: Programiranje
191313 (930) detroit
»

[Android] Thread

Oddelek: Programiranje
8990 (767) Spura
»

[android] vstavljanje slike

Oddelek: Programiranje
7978 (875) messi
»

[Android]Cudno obnasanje aplikacije in emulatorja

Oddelek: Programiranje
71068 (897) KernelPanic
»

[JAVA] zaustavitev niti (threadov)

Oddelek: Programiranje
222769 (2769) morbo

Več podobnih tem