IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Android Discussion :

Bluetooth changement d'activity


Sujet :

API standards et tierces Android

  1. #1
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut Bluetooth changement d'activity
    Bonjour,

    Je développe une appli utilisant le bluetooth, pour cela je me suis servie du code fourni par Eclipse "BluetoothChat", cependant j'ai un souci dans mon application, je ne peu pas changer d'écran (d'activity) sans que cela coupe la liaison bluetooth, auriez-vous une idée des variables ou autres à mettre en commun aux différentes activities ?

    Merci d'avance

  2. #2
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mai 2013
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2013
    Messages : 20
    Points : 31
    Points
    31
    Par défaut
    Bonjour,

    J'ai moi même développé une application utilisant le Bluetooth. Mais j'ai fais en sorte de ne pas changer d'Activity lorsque la connexion était établie.

    Sinon je pense qu'on peut utiliser un Service qui restera actif lors du passage d'une Activity à une autre.

  3. #3
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    D'accord mais dans mon cas je suis obligé de changer d'activité, pouvez-vous développer les "services" ?

  4. #4
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Un service peut être vu comme une activité... sans interface.
    (même restrictions, mêmes possibilités, mais pas de fenêtre/view associée).

    Le service peut donc "maintenir" la connexion BT, en parallèle d'une activité normale (qui y fait accès par un simple "bindService").
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  5. #5
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Très bien merci je me penche la dessus.

  6. #6
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Alors j'ai ca :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    ///////////////////////////////////////////////////////////////////////////////////////////////////
    	///////////////////////////////////////////////////////////////////////////////////////////////////	
    	//////////////////////////////////////////////onDestroy////////////////////////////////////////////
    	///////////////////////////////////////////////////////////////////////////////////////////////////
    	///////////////////////////////////////////////////////////////////////////////////////////////////
     
        //The final call you receive before your activity is destroyed. 
        //This can happen either because the activity is finishing (someone called finish() on it,
        //or because the system is temporarily destroying this instance of the activity to save space.
        //Next : NOTHING
        public void onDestroy() {
            super.onDestroy();
            // Stop the Bluetooth chat services
            if (mChatService != null) mChatService.stop();
            if(D) Log.e(TAG, "--- ON DESTROY ---");
        }
    Dois-je du coup enlever la condition ?

  7. #7
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    coté activité... il n'y a que "bind" et "unbind"....
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  8. #8
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Heu je n'ai pas compris ?

  9. #9
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Voila le code pour la communication :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    package com.example.convertisseurpuissance;
     
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Set;
    import java.util.UUID;
     
    import android.app.Service;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
     
    public class BtInterface  {
     
    	private BluetoothDevice device = null;
    	private BluetoothSocket socket = null;
    	private InputStream receiveStream = null;
    	private OutputStream sendStream = null;
     
    	private ReceiverThread receiverThread;
     
    	Handler handler;
     
    	public BtInterface(Handler hstatus, Handler h) {
    		Set<BluetoothDevice> setpairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    		BluetoothDevice[] pairedDevices = (BluetoothDevice[]) setpairedDevices.toArray(new BluetoothDevice[setpairedDevices.size()]);
     
    		for(int i=0;i<pairedDevices.length;i++) {
    			if(pairedDevices[i].getName().contains("Free2move WU")) {
    				device = pairedDevices[i];
    				try {
    					socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
    					receiveStream = socket.getInputStream();
    					sendStream = socket.getOutputStream();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    				break;
    			}
    		}
     
    		handler = hstatus;
     
    		receiverThread = new ReceiverThread(h);
    	}
     
    	public void sendData(String data) {
    		sendData(data, false);
    	}
     
    	public void sendData(String data, boolean deleteScheduledData) {
    		try {
    			sendStream.write(data.getBytes());
    	        sendStream.flush();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
     
    	public void connect() {
    		new Thread() {
    			@Override public void run() {
    				try {
    					socket.connect();
     
    					Message msg = handler.obtainMessage();
    					msg.arg1 = 1;
    	                handler.sendMessage(msg);
     
    					receiverThread.start();
     
    				} catch (IOException e) {
    					Log.v("N", "Connection Failed : "+e.getMessage());
    					e.printStackTrace();
    				}
    			}
    		}.start();
    	}
     
    	public void stop() {
    		try {
    			socket.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
     
    	public BluetoothDevice getDevice() {
    		return device;
    	}
     
     
    	private class ReceiverThread extends Thread {
    		Handler handler;
     
    		ReceiverThread(Handler h) {
    			handler = h;
    		}
     
    		@Override public void run() {
    			while(true) {
    				try {
    					if(receiveStream.available() > 0) {
     
    						byte buffer[] = new byte[100];
    						int k = receiveStream.read(buffer, 0, 100);
     
    						if(k > 0) {
    							byte rawdata[] = new byte[k];
    							for(int i=0;i<k;i++)
    								rawdata[i] = buffer[i];
     
    							String data = new String(rawdata);
     
    							Message msg = handler.obtainMessage();
    							Bundle b = new Bundle();
    							b.putString("receivedData", data);
    			                msg.setData(b);
    			                handler.sendMessage(msg);
    						}
    					}
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
     
     
    }
    Et la le main (c'est le code original que j'ai trouvé, le mien diffère mais ce sont des choses indépendantes du bluetooth :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
     
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
     
    public class MonApp extends Activity implements OnClickListener {
    	private TextView logview;
    	private EditText sendtext;
    	private Button connect, send;
     
    	private BtInterface bt = null;
     
    	private long lastTime = 0;
     
    	final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                String data = msg.getData().getString("receivedData");
     
                long t = System.currentTimeMillis();
                if(t-lastTime > 100) {// Pour Èviter que les messages soit coupÈs
                    logview.append("\n");
    				lastTime = System.currentTimeMillis();
    			}
                logview.append(data);
            }
        };
     
        final Handler handlerStatus = new Handler() {
            public void handleMessage(Message msg) {
                int co = msg.arg1;
                if(co == 1) {
                	logview.append("Connected\n");
                } else if(co == 2) {
                	logview.append("Disconnected\n");
                }
            }
        };
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
            bt = new BtInterface(handlerStatus, handler);
     
            logview = (TextView)findViewById(R.id.logview);
            sendtext = (EditText)findViewById(R.id.sendtxt);
     
            connect = (Button)findViewById(R.id.connect);
            connect.setOnClickListener(this);
     
            send = (Button)findViewById(R.id.send);
            send.setOnClickListener(this);
        }
     
    	@Override
    	public void onClick(View v) {
    		if(v == connect) {
    			bt.connect();
    		} else if(v == send) {
    			bt.sendData(sendtext.getText().toString());
    		}
    	}
    }
    Pourriez-vous m'éclairer sur ce que je dois faire pour maintenir la connexion BT car je ne vois pas du tout ?

    Merci

  10. #10
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2013
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2013
    Messages : 9
    Points : 8
    Points
    8
    Par défaut
    Bonjour tout le monde.
    Je me permet de poster ici car c'est exactement ce problème qui m’amène.
    En fouillant sur internet, j'ai bien vu que créer un service était possible cependant j'ai trouvé une autre solution proposé sur stackoverflow.

    Celle de passer par une classe application.
    Problème mon application ne démarre même plus et je ne sais pas d'où cela peut venir.

    J'aimerais savoir si cette solution est viable et si oui, être orienté sur le pourquoi de mon problème.

    Voici une partie de mon code :
    Ma classe bluetooth :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class BtClass extends Activity{
     
            private final BluetoothAdapter blueAdapter;
     
     
            public BtClass()
            {
                    blueAdapter = BluetoothAdapter.getDefaultAdapter();
            }
    ....
    Mon main :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    public class MainActivity extends Activity implements  OnClickListener {
    	private ListView liste;
    	private long lastTime = 0;
    	public TextView logview;
    	private Button connect;
    	public BtClass bt = null;
    	private ToggleButton bluetooth;
    	private Set<BluetoothDevice> KnownDevices;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
     
            Log.d("debug","Commencement");
            MyApplication appState = ((MyApplication)getApplicationContext());
            Log.d("debug","Context de MyApplication recuperé");
            bt = appState.CreateBtDevice();
            Log.d("debug","bt recuperé");
     
     
            liste=(ListView) findViewById(R.id.listView);
            logview = (TextView)findViewById(R.id.logview);
            bluetooth = (ToggleButton)findViewById(R.id.bluetooth);
            bluetooth.setOnClickListener(this);
            connect = (Button)findViewById(R.id.lie);
            connect.setOnClickListener(this);
    Ma classe Application qui permet de recuperer le btAdapter si j'ai bien compris:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    public class MyApplication extends Application {
     
     
        private  BtClass bt = null;    
     
        public BtClass getBtDevice(){
        	Log.d("debug","getBtDevice");
          return bt;
        }
        public BtClass CreateBtDevice(){
        	Log.d("debug","in CreationBtDevice");
        	 bt = new BtClass();
        	 Log.d("debug","bt create in createBtDevice");
        	 return bt;
        }
    }
    Mon manifest :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.sevice_bluetooth"
        android:versionCode="1"
        android:versionName="1.0" >
     
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />
            <uses-permission android:name="android.permission.BLUETOOTH"/>
         	<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     
     
     
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.sevice_bluetooth.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
     
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
                </activity>
                <activity
                	android:name=".manette_class"
                	android:screenOrientation="landscape">
     
           		 </activity>
     
     
     
         </application>
          <application 
      		    android:name=".MyApplication" 
         	  	android:icon="@drawable/icon" 
         		android:label="@string/app_name"
          		android:allowBackup="false"/>
     
     
     
     
    </manifest>
    Et pour finir mon erreur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    07-11 17:38:06.713: D/debug(20180): Commencement
    07-11 17:38:06.723: D/AndroidRuntime(20180): Shutting down VM
    07-11 17:38:06.723: W/dalvikvm(20180): threadid=1: thread exiting with uncaught exception (group=0x40ab6228)
    07-11 17:38:06.723: E/AndroidRuntime(20180): FATAL EXCEPTION: main
    07-11 17:38:06.723: E/AndroidRuntime(20180): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sevice_bluetooth/com.example.sevice_bluetooth.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.sevice_bluetooth.MyApplication
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2205)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.ActivityThread.access$600(ActivityThread.java:139)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.os.Handler.dispatchMessage(Handler.java:99)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.os.Looper.loop(Looper.java:156)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.ActivityThread.main(ActivityThread.java:4987)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at java.lang.reflect.Method.invokeNative(Native Method)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at java.lang.reflect.Method.invoke(Method.java:511)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at dalvik.system.NativeStart.main(Native Method)
    07-11 17:38:06.723: E/AndroidRuntime(20180): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.sevice_bluetooth.MyApplication
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at com.example.sevice_bluetooth.MainActivity.onCreate(MainActivity.java:43)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.Activity.performCreate(Activity.java:4538)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
    07-11 17:38:06.723: E/AndroidRuntime(20180): 	... 11 more
    Au début je pensais que le problème venait de mon manifest mais malgré mes recherches je n'ai pas su debugger le code.

    Merci par avance pour votre aide.

  11. #11
    Membre éprouvé
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    757
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 757
    Points : 968
    Points
    968
    Par défaut
    Pour ton erreur, elle vient du fait que tu n'as pas déclaré ta nouvelle classe qui hérite de Application dans le fichier Manifest.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
       <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >

  12. #12
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Si ton code fonctionne pourrais-tu le poster pour que je m'en inspire ? Merci bien

  13. #13
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2013
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2013
    Messages : 9
    Points : 8
    Points
    8
    Par défaut
    Il y a pourtant bien, dans le Manifest :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     <application 
      		android:name=".MyApplication" 
         	  	android:icon="@drawable/icon" 
         		android:label="@string/app_name"
          		android:allowBackup="false"/>
    Et en remplaçant celui-ci par ta réponse Simon, j'obtiens toujours la même erreurs.

  14. #14
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    parcequ'il y a 2 applications définies dans le manifest ?
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  15. #15
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2013
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2013
    Messages : 9
    Points : 8
    Points
    8
    Par défaut
    Ok. Merci Nicroman pour cette petite question qui ma fait comprendre l’énormité de l'erreur.

    (je ne suis pas totalement au point au niveau du Manifest encore, et je me suis corrigé en m'inspirant à la base d'un code pipé..)
    Encore merci.
    Katze, je peaufine ça demain (car je n'ai pas le module bluetooth sous la main) et je t'envoie ça.

    EDIT :
    Voici le code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    package com.example.sevice_bluetooth;
     
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Set;
    import java.util.UUID;
     
    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.Context;
    import android.os.Parcel;
    import android.os.Parcelable;
    import android.util.Log;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
     
    public class BtClass extends Activity{
     
            private final BluetoothAdapter blueAdapter;
          //  private final MyBroadcastReceiver blueReceiver;
            protected Set<BluetoothDevice> mArrayAdapter;
            Set<BluetoothDevice> setpairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
            BluetoothDevice[] pairedDevices = (BluetoothDevice[]) setpairedDevices.toArray(new BluetoothDevice[setpairedDevices.size()]);
            private BluetoothSocket socket = null;
            private BluetoothDevice device = null;// le périphérique (le module bluetooth)
            private InputStream receiveStream = null;// Canal de réception
            private OutputStream sendStream = null;// Canal d'émission
            boolean stopWorker = false;
            String Message;
     
            public BtClass()
            {
                    blueAdapter = BluetoothAdapter.getDefaultAdapter();
            }
     
            public String GetEtat()
            {
            	    String returnedString = "";
                    if (blueAdapter.isEnabled()) {
                    	 returnedString = "Bluetooth enable";
                    }
                    else
                    {
                    	 returnedString = "Bluetooth disable";
                    }
                    return returnedString;
     
            }
     
            public String ActivateBlue()
            {
     
                    String returnedString = "";
     
                    if (!blueAdapter.isEnabled()) {
                            try {
                                    blueAdapter.enable();
     
                             returnedString = "Le Bluetooth est activé";
                            }
                            catch(Exception e)
                            {
                                    returnedString = "Erreur : " + e.toString();
                            }
     
     
                    }
                    return returnedString;
     
            }
     
            public String DisactivateBlue(){
            	 String returnedString = "";
     
                 if (blueAdapter.isEnabled()) {
                         try {
                        	 blueAdapter.disable();
                          returnedString = "Le Bluetooth est desactivé";
     
                         }
                         catch(Exception e)
                         {
                                 returnedString = "Erreur : " + e.toString();
                         }
     
     
                 }
                 return returnedString;
            }
     
     
     
            public Set<BluetoothDevice> KnownDevices()
            {
                    Set<BluetoothDevice> pairedDevices = blueAdapter.getBondedDevices();
                    return pairedDevices;
            }
     
     
            public void ScanDevices(Context context)
            {
                    try{
                            Toast.makeText(BtClass.this, "demarage de la decouverte ", Toast.LENGTH_SHORT).show();
                            //blueAdapter.startDiscovery();
                    }catch (Exception e) {
                            Toast.makeText(BtClass.this, "erreur : " + e, Toast.LENGTH_SHORT).show();
                    }
     
                    //return pairedDevices;
            }
     
            protected void onDestroy() {
                      super.onDestroy();
                      blueAdapter.cancelDiscovery();
                   //   unregisterReceiver(blueReceiver);
            }
     
     
            public boolean ConnectDevice(ListView liste, int myItemInt, TextView reception)
            {
            	reception.append("\n wait...");
            	for(int i=0;i<pairedDevices.length;i++)
      	        {
      	            // On teste si ce périphérique contient le nom du module bluetooth connecté au microcontrôleur
      	        	Log.d("debug", "Boucle des paires devices");
      	          String selectedFromList =(String) (liste.getItemAtPosition(myItemInt));
      	            if(pairedDevices[i].getName().contains(selectedFromList)) {
      	            	Log.d("debug", selectedFromList+" find");
      	                device = pairedDevices[i];
      	                try {
      	            		String ADR=device.getAddress();
    	                    // On récupère le socket de notre périphérique
    	                	Log.d("debug","adresse device : "+ ADR);	                    
    	                    BluetoothDevice device = blueAdapter.getRemoteDevice(ADR);
    	            		Log.d("debug", "Connecting to ... " + device);
    	            		reception.setText("Connecting to ... " + device);
    	            		blueAdapter.cancelDiscovery();
    	            		socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
    	            		Log.d("debug", "peut etre");
    	            		reception.append("\n wait...");
    	            		socket.connect();
    	            		Log.d("debug", "connecté !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    	            		reception.setText("Device Connecte \n Wait... ");
     
    	            		beginListenForData(reception);
    	            		Log.d("debug", "receiverThread.start();");
    	            		return true;
     
     
      	                } catch (IOException e) {
      	                    e.printStackTrace();
      	                    Log.d("debug", "connection fail");
      	                  reception.setText("Fail Connection");
     
      	                    return false;
     
      	                }
     
      	            }   
      	        }
    			return stopWorker;
     
      	      }                     
     
     
            public void DisconnectionDevice()
            {
     
            }
     
            public List<String> PutInList(ListView liste)
            {
     
            	Log.d("debug", "rentré");
     
             	Log.d("debug", "Tableau de device");
                 List<String> BlueDevicesList=new ArrayList<String>();
             	Log.d("debug", "rentre dans le for");
                 for(int i=0;i<pairedDevices.length;i++)
                 {
                		Log.d("debug", "IN");
                 	  BlueDevicesList.add(pairedDevices[i].getName()); 
                 }
             	Log.d("debug", "OUT");
             	return BlueDevicesList;
     
            }
     
        	public void writeData(String data) {
    			try {
    				sendStream = socket.getOutputStream();
    			} catch (IOException e) {
    				Log.d("debug", "Bug BEFORE Sending stuff", e);
    			}
     
    			String message = data;
     
    			byte[] msgBuffer = message.getBytes();
     
    			try {
    				sendStream.write(msgBuffer);
    			} catch (IOException e) {
    				Log.d("debug", "Bug while sending stuff", e);
    			}
    		}
        	public void writeData(int number) {
    			try {
    				sendStream = socket.getOutputStream();
    			} catch (IOException e) {
    				Log.d("debug", "Bug BEFORE Sending stuff", e);
    			}
     
    			int message = number;
     
    			byte msgBuffer =(new Integer(message)).byteValue();
    			try {
    				sendStream.write(msgBuffer);
    			} catch (IOException e) {
    				Log.d("debug", "Bug while sending stuff", e);
    			}
    		}
     
     
     
            public void beginListenForData(final TextView reception)   {
    			 try {
    				 Log.d("debug", "creation de receivestream");
    				 receiveStream = socket.getInputStream();
    				} catch (IOException e) {
    				}
     
    		        Thread workerThread = new Thread(new Runnable()
    		        {
    		            public void run()
    		            {    
    		            	 Log.d("debug", "run de threadWorker");
    		            	 while(!Thread.currentThread().isInterrupted() && !stopWorker)
    			               {
    		            		//Log.d("debug","post try");
    		                    try 
    		                    {
    		                    	//Log.d("debug","try");
    		                    	if(receiveStream.available() > 0)
    		                        {
    		                    		 Log.d("debug", "Available OK");
    		                    		byte buffer[] = new byte[100];
     
    		                            // On lit les données, k représente le nombre de bytes lu
    		                            int k = receiveStream.read(buffer, 0, 100);
    		                            Log.d("debug", "Lecture Bugger : OK");
    		                            if(k > 0) {
     
    		                                // On convertit les données en String
    		                            	  Log.d("debug", "Conversion donnée");
    		                                byte rawdata[] = new byte[k];
    		                            	  Log.d("debug", "Nouveau tableau de Byte");
    		                                for(int i=0;i<k;i++){
    			                            	  Log.d("debug", "Boucle for : check");
    		                                    rawdata[i] = buffer[i];
    			                            	  Log.d("debug", "Rawdata = buffer");
    		                                }
    		                                String data = new String(rawdata);
    		                                Log.d("debug", "new string");
    		                                Message=data;
     
    		                               //a faire dans le Thread UI
    		                                runOnUiThread(new Runnable() {
    		                                	public void run() {
    		                                	reception.setText(" "+Message);
    		                                	}
    		                                }
    		                            );
     
    		                              Log.d("debug", data);
    		                            }
    		                        }    
     
    		                    } 
    		                    catch (IOException ex) 
    		                    {
    		                    	 Log.d("debug", "marche pas");
    		                    	 stopWorker = true;
     
    		                    }
    			               }
    		            }
    		        });
     
    		        workerThread.start();
    		    }
     
     
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    package com.example.sevice_bluetooth;
     
    import android.app.Application;
    import android.util.Log;
     
    public class MyApplication extends Application {
     
     
        private  BtClass bt = null;    
     
        public BtClass getBtDevice(){
        	Log.d("debug","getBtDevice");
          return bt;
        }
        public BtClass CreateBtDevice(){
        	Log.d("debug","in CreationBtDevice");
        	 bt = new BtClass();
        	 Log.d("debug","bt create in createBtDevice");
        	 return bt;
        }
     
        /*private BtClass bt = null;    
     
       
        public synchronized BtClass getBtConnection() {
            Log.d("debug","In application");
            if ( bt == null) {
                Log.d("debug","In If Application");
                // construct a BluetoothDevice object and put it into variable device
            	 bt = new BtClass();
            	    Log.d("debug","bt creation");
            }
            return  bt;
     
        }
        */
     
    }

  16. #16
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Merci c'est sympa, je test ca la semaine prochaine et je te dit si ca a marché de mon côté.

  17. #17
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    Donc en regardant ton code je me demandais : On m'a parlé des Services mais je en le vois pas dans ton code ? Je ne comprend pas trop comment mettre en place cette "Activité invisible".

  18. #18
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Le service permet de résister à la disparition de toutes les activités....
    Ce qui n'est pas forcément le cas d'une implémentation dans l'application.

    Mais les deux sont possible.

    Une troisieme méthode est une méthode d'instance statique:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
     
    class BTManager
    {
         private static WeakReference<BTManager> _instance = null;
     
         public static synchronized BTManager getInstance() {
             BTManager ret = (_instance == null) ? null : _instance.get();
             if (ret == null) {
                 ret = new BTManager();
                 _instance = new WeakReference<BTManager>(ret);
             }
             return ret;
         }
    }
    Tant qu'une activité utilise un BTManager, c'est toujours la même instance (le même objet), il peut donc gérer des threads, des connexions, etc...
    Quand plus personne n'utilise le BTManager il est "garbage-collected" et une nouvelle instance sera créée si nécessaire.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  19. #19
    Membre régulier
    Homme Profil pro
    Software Engineer
    Inscrit en
    Février 2013
    Messages
    139
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2013
    Messages : 139
    Points : 94
    Points
    94
    Par défaut
    D'accord donc je dois créer un BTManager lors de la création de ma connexion BT ?

  20. #20
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2013
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2013
    Messages : 9
    Points : 8
    Points
    8
    Par défaut
    Bonjour.

    Je reviens par ici, car j'ai toujours quelques soucis avec ma connexion android.
    J'arrive bien à garder ma connexion bluetooth à travers les activités mais cette fois je n'arrive pas à adapter l'affichage des données reçut en fonction de l'activité active.

    Je m'explique : via l’activité 1, je crée la connexion et met en place un système d’écoute en cas de réception de donnée.
    Si des données sont reçut, j'affiche celle-ci dans un TextView.

    Et je passe directement à l'activité 2.
    Problème le TextView de réception n'existe plus.

    Et plutôt que de continuer dans la voie d'une implémentation dans l'application. Je me suis dis qu'il serait plus judicieux et probablement plus propre de reprendre le tout avec un service adapté.
    Mais je dois dire que j'ai un peu de mal avec cette notion.

    Je vois bien le principe et les indications microman m'ont quelques peu éclairées mais pas suffisamment pour m'en sortir.

    J'aurais bien aimé avoir un peu plus d'information sur comment m'y prendre.

    Merci par avance.

Discussions similaires

  1. Réponses: 3
    Dernier message: 06/06/2015, 04h36
  2. Réponses: 3
    Dernier message: 10/08/2014, 00h38
  3. Orientation changement d'activity
    Par zarktoune dans le forum Android
    Réponses: 2
    Dernier message: 12/10/2011, 15h34
  4. Détecter le changement fenêtre active
    Par zsoh dans le forum Langage
    Réponses: 6
    Dernier message: 12/07/2011, 11h37
  5. Réponses: 3
    Dernier message: 25/06/2007, 15h25

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo