не могу получить точный график, используя диаграмму mpandroid - PullRequest
0 голосов
/ 08 марта 2019

Я создал приложение для наблюдения графика в реальном времени. Поэтому я дал сигнал синусоидальной волны, как этот

введите описание изображения здесь

но когда я пытаюсь запустить волновую форму в своем приложении, я получаю вот так. введите описание изображения здесь

это мой код Android

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

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

import static android.content.ContentValues.TAG;

public class bluetooth extends Activity implements AdapterView.OnItemClickListener {

    public static void  disconnect(){
        if (connectedThread !=null){
            connectedThread.cancel();
            connectedThread= null;
        }
    }

    public static void gethandler(Handler handler){

        mHandler= handler;
    }

    static  Handler mHandler =new Handler();

    static ConnectedThread connectedThread;
    public static final UUID my_UUID= UUID.fromString("f53a07d4-3010-11e9-b210-d663bd873d93");

protected static final int SUCCESS_CONNECT=0;
protected static final int MESSAGE_READ=1;
ListView listView;
//ArrayAdapter is an Android SDK class for adapting an array of objects as a datasource.
// Adapters are used by Android to treat a result set uniformly whether it's from a database, file, or in-memory objects
// so that it can be displayed in a UI element.
// The ArrayAdapter is useful for the latter. Use it anywhere you would use an Adapter. E.g. attach to Android UI elements.
ArrayAdapter<String> list_adapter;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;

///ArrayList is an implementation of java.util.List that's backed by an array. You can use it anywhere you would use a java.util.List.
//// E.g. where you need to maintain order of a collection of objects where duplicates are allowed.
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;
    BluetoothDevice device;



    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //in Android the visual design is created in xml . And each Activity is associated to a design
        //
        //setContentView(R.layout.main)
        //R means Resource
        //
        //layout means design
        //
        //main is the xml you have created under res->layout->main.xml
        //
        //Whenever you want to change your current Look of an Activity or when you move from
        // one Activity to another . The other Activity must have a design to show . So we call this method in onCreate
        // and this is the second statement to set the design
       setContentView(R.layout.activity_bluetooth);
        init();

if(btAdapter==null){
    Toast.makeText(getApplicationContext(),"no bt detected", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "onCreate: no");
    finish();
}
else{
    if(!btAdapter.isEnabled()){
        turnOnBT();
    }


    getPairedDevices();
   startDiscovery();
}
    }

private void  getPairedDevices(){
        btAdapter.cancelDiscovery();
        btAdapter.startDiscovery();
}

    private void  turnOnBT(){
        Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent,1);
    }

    private void  startDiscovery(){
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray)
            if (device != null) {
                devices.add(device);
                list_adapter.add(device.getName()+" "+"(paired)"+""+"\n"+device.getAddress());
            }


            }
        }


    private void init() {
        listView =(ListView)findViewById(R.id.list_item);
        listView.setOnItemClickListener(this);
        list_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
        listView.setAdapter(list_adapter);
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        pairedDevices =new ArrayList<String>();
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        devices = new ArrayList<BluetoothDevice>();

        receiver =new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action =intent.getAction();
                if(BluetoothDevice.ACTION_FOUND.equals(action)){
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    devices.add(device); //!!!!!!!!!!
                    String s="";
                    for (int a=0;a<pairedDevices.size();a++){
                        if(device.getName().equals(pairedDevices.get(a))){
                            s="(paired)";
                            break;
                        }
                    }
                    list_adapter.add(device.getName()+" "+s+""+"\n"+device.getAddress());

                }
                else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

                }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

                }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                    if(btAdapter.getState()==btAdapter.STATE_OFF){
                        turnOnBT();
                    }
                }
            }



        };
        //An Intent is a simple message object that is used to communicate between android components such as activities,
        // content providers, broadcast receivers and services. Intents are also used to transfer data between activities.


        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(btAdapter.isDiscovering()){
            btAdapter.cancelDiscovery();

        }
        if(list_adapter.getItem(position).contains("(paired)")){
            BluetoothDevice selectedDevice = devices.get(position);
            ConnectThread connect = new ConnectThread(selectedDevice);
            connect.start();
        }
        else{
            Toast.makeText(getApplicationContext(),"device not paired", Toast.LENGTH_SHORT).show();
        }
    }



    private class ConnectThread extends Thread {
        private BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;



        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice=device;

            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                // MY_UUID is the app's UUID string, also used by the server code
                tmp = device.createRfcommSocketToServiceRecord(my_UUID);
            } catch (IOException e) { }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discover y because it will slow down the connection
            btAdapter.cancelDiscovery();

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                //connectedThread = new ConnectedThread(mmSocket);
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                Log.i(TAG, "run: >>> " + connectException.getLocalizedMessage());
                // Unable to connect; close the socket and try the fallback method of reflection with port to connect
                try {
                    Log.e("", "trying fallback...");

                    mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1);
                    Log.v(TAG, "Client Connect Again Attempt 2, but with fall back Reflection and port");
                    mmSocket.connect();

                    Log.e("", "Connected");

                } catch (Exception ex) {
                    Log.e("", "Couldn't establish Bluetooth connection!");
                    return;


                }

               // try {
                 //   mmSocket.close();
               // } catch (IOException closeException) { }
                //return;
            }

            // Do work to manage the connection (in a separate thread)
            Log.i(TAG, "run: >>> Device connected...");
            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
        }

        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {

                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    // Incoming and the outgoing strings are carried out inside this thread read is for reading incoming messages through a socket and write is for sending messages to the remote device
    static 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;
            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                // socket not created
                e.printStackTrace();
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        StringBuffer sbb = new StringBuffer();
        public void run() {
            byte[] buffer ;
            int bytes;
            // receiving message
          while(true) {
              try {
                  try {
                      sleep(30);
                  } catch (InterruptedException e) {
                      break;
                  }

                  buffer = new byte[1024];
                  // Read from the InputStream
                  bytes = mmInStream.read(buffer);
                  // message is in bytes form so reading them to obtain message

                  mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
              } catch (IOException e) {
                  // connection was lost and start your connection again
                  Log.e(TAG, "disconnected", e);
                  break;
              }
          }
        }

        public void write(String income) {
            try {
                mmOutStream.write(income.getBytes());
                for (int i=0;i<income.getBytes().length;i++)
                    Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
                try{
                Thread.sleep(20);
                }
                catch (InterruptedException e1){
                e1.printStackTrace();

                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            }
            public void cancel(){
            try {
                mmSocket.close();
            }
            catch (IOException e){}
            }
        }
}

, так что подумайтепроблема с моим кодом Android. Но я не знаю, как это исправить. Как я могу получить синусоидальную форму в моем приложении. Любая помощь по этому вопросу будет принята с благодарностью.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...