0

所以,我在一个网站上看到了一个使用蓝牙连接到微控制器的程序,但正如你在下面看到的......

06-20 15:11:02.937: D/AndroidRuntime(218): Shutting down VM
06-20 15:11:02.937: W/dalvikvm(218): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
06-20 15:11:02.937: E/AndroidRuntime(218): Uncaught handler: thread main exiting due to uncaught exception
06-20 15:11:03.047: E/AndroidRuntime(218): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{depthermique.transfert.bluetooth/depthermique.transfert.bluetooth.TransfertBluetooth}: java.lang.ClassNotFoundException: depthermique.transfert.bluetooth.TransfertBluetooth in loader dalvik.system.PathClassLoader@43d0bae8
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.os.Looper.loop(Looper.java:123)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.ActivityThread.main(ActivityThread.java:4363)
06-20 15:11:03.047: E/AndroidRuntime(218):  at java.lang.reflect.Method.invokeNative(Native Method)
06-20 15:11:03.047: E/AndroidRuntime(218):  at java.lang.reflect.Method.invoke(Method.java:521)
06-20 15:11:03.047: E/AndroidRuntime(218):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
06-20 15:11:03.047: E/AndroidRuntime(218):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-20 15:11:03.047: E/AndroidRuntime(218):  at dalvik.system.NativeStart.main(Native Method)
06-20 15:11:03.047: E/AndroidRuntime(218): Caused by: java.lang.ClassNotFoundException: depthermique.transfert.bluetooth.TransfertBluetooth in loader dalvik.system.PathClassLoader@43d0bae8
06-20 15:11:03.047: E/AndroidRuntime(218):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
06-20 15:11:03.047: E/AndroidRuntime(218):  at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
06-20 15:11:03.047: E/AndroidRuntime(218):  at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
06-20 15:11:03.047: E/AndroidRuntime(218):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
06-20 15:11:03.047: E/AndroidRuntime(218):  ... 11 more
06-20 15:11:03.121: I/dalvikvm(218): threadid=7: reacting to signal 3
06-20 15:11:03.138: I/dalvikvm(218): Wrote stack trace to '/data/anr/traces.txt'

......它没有按计划进行。

我不认为是我改变的东西导致了这种情况,因为我只改变了一两件事。不过这只是一个希望。

我已经在网上和这个网站上进行了研究,但是,即使有看起来像我的问题,它对我所拥有的还不够具体。谈到代码,它是:

MonApp.java

package depthermique.transfert.bluetooth;

import android.annotation.SuppressLint;
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;

@SuppressLint("HandlerLeak")
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;

@SuppressLint("HandlerLeak")
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.activity_transfert_bluetooth);

    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());
    }
}
}

Btinterface.java

package depthermique.transfert.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

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; //le périphérique (le module bluetooth)
private BluetoothSocket socket = null;
private InputStream receiveStream = null; //Canal de reception
private OutputStream sendStream = null; //Canal d'émission

private ReceiverThread receiverThread;

Handler handler;

//On récupère la liste des périphériques associés
public BtInterface(Handler hstatus, Handler h) 
{
    Set<BluetoothDevice> setpairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    BluetoothDevice[] pairedDevices = (BluetoothDevice[]) setpairedDevices.toArray(new BluetoothDevice[setpairedDevices.size()]);

    //On parcours la liste pour trouver notre module bluetooth
    for(int i=0;i<pairedDevices.length;i++) 
    {
        //On teste si ce périphérique contient le nom du module bluetooth connecté au microcontroleur
        if(pairedDevices[i].getName().contains("ModuleBluetooth")) 
        {
            device = pairedDevices[i];
            try 
            {
                //On récupère la socket de notre périphérique
                socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                receiveStream = socket.getInputStream(); //Canal de réception (valide uniquement après la connection)
                sendStream = socket.getOutputStream(); //Canal d'émission (valide uniquement aptès la connection)
            } 
            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(); //Tentative de connection

                Message msg = handler.obtainMessage();
                msg.arg1 = 1;
                handler.sendMessage(msg);

                receiverThread.start();
                //Connexion réussie
            } 
            catch (IOException e) {

                //Echec de la connection
                Log.v("N", "Connection Failed : "+e.getMessage());
                e.printStackTrace();
            }
        }
    }.start();
}

public void close() 
{
    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();
            }
        }
    }
}

}

activity_transfert_bluetooth.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Connection" >
    </Button>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/sendtxt"
            android:layout_width="224dp"
            android:layout_height="wrap_content"
            android:text="" >
        </EditText>

        <Button
            android:id="@+id/send"
            android:layout_width="94dp"
            android:layout_height="wrap_content"
            android:text="Envoyer" >
        </Button>
    </LinearLayout>

    <TextView
        android:id="@+id/logView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:bufferType="editable" />

</LinearLayout>

而且,就是这样。如果这很明显,很抱歉我看不到它,我两天前才开始“学习” android,而且我对 Java 也不是很熟悉。我希望有人能够帮助我解决这个问题。

编辑:我在这里添加 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest 
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="depthermique.transfert.bluetooth"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="depthermique.transfert.bluetooth.TransfertBluetooth"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
4

2 回答 2

0

您是否将权限添加到 AndroidManifest ?

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.app.myapp" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    ...
</manifest>
于 2013-06-20T14:04:55.953 回答
0

原来的例外是:

06-20 15:11:03.047: E/AndroidRuntime(218): Caused by: java.lang.ClassNotFoundException: depthermique.transfert.bluetooth.TransfertBluetooth in loader dalvik.system.PathClassLoader@43d0bae8

翻译:系统找不到TransfertBluetooth课程。这是您在AndroidManifext.xml.

但是你在java源代码中的类名是不同的:

public class MonApp extends Activity implements OnClickListener {...}

将类名更改为TransfertBluetooth或更改AndroidMaifest.xml为:

<activity
            android:name="depthermique.transfert.bluetooth.MonApp"

源代码中的类名和源代码中的类名AndroidManifest.xml必须相同。

于 2013-06-22T12:51:56.423 回答