如何使方法在Android中反复运行?

时间:2019-03-02 15:43:10

标签: android arduino

所以我的项目包括一个光强度传感器和一个Android应用程序。我的Android Studio中有一个方法,我想重复运行,它的作用是从arduino接收数据。该方法从arduino接收数据并将其打印在logcat中。我见过asynctask或某些线程方法之类的东西。任何人都可以阐述或建议我可以尝试的东西吗?谢谢。

我的arduino代码:

#include <Wire.h>
#include <BH1750.h>
#include <SoftwareSerial.h>

BH1750 lightMeter;
SoftwareSerial BTSerial(0,1); //RX | TX

void setup(){
  Serial.begin(9600);
  lightMeter.begin();
  BTSerial.begin(4800);
  Serial.println("Running...");
}


void loop() {
  uint16_t lux = lightMeter.readLightLevel();
  Serial.print("Light: ");
  Serial.print(lux);
  Serial.println(" lx");
  if (lux <= 0) {
    BTSerial.print("#");
    Serial.println("sending to android");
  }
  delay(1000);
}

我的android代码:

package com.example.android.cigarettebox;

import android.bluetooth.BluetoothServerSocket;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;

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

import static com.example.android.cigarettebox.R.id.textView;

public class Menu extends ActionBarActivity {

    Button btnOn, btnOff, btnDis,btnPage1, guides;
    String address = null;
    TextView testings;

    private ProgressDialog progress;
    BluetoothAdapter myBluetooth = null;
    BluetoothSocket btSocket = null;
    private boolean isBtConnected = false;
    private InputStream inputStream;

    //SPP UUID. Look for it
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

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

        Intent newint = getIntent();
        address = newint.getStringExtra(com.example.android.cigarettebox.DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device

        //view of the Menu
        setContentView(R.layout.activity_menu);

        //call the widgtes
        btnOn = (Button)findViewById(R.id.button2);
        btnOff = (Button)findViewById(R.id.button3);
        btnDis = (Button)findViewById(R.id.button4);
        btnPage1 = (Button) findViewById(R.id.button6);
        guides = (Button) findViewById(R.id.guide);
        testings = (TextView) findViewById(R.id.test);

        new ConnectBT().execute(); //Call the class to connect

        //commands to be sent to bluetooth
        btnOn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                turnOnLed();      //method to turn on
            }
        });

        btnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                turnOffLed();   //method to turn off
            }
        });

        btnDis.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Disconnect(); //close connection
            }
        });

        btnPage1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // Make an intent to start next activity.
                Intent intent = new Intent(v.getContext(), page1.class);
                startActivity(intent);
            }
        });

        guides.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // Make an intent to start next activity.
                Intent intent = new Intent(v.getContext(), page4.class);
                startActivity(intent);
            }
        });
    }

    private void Disconnect()
    {
        if (btSocket!=null) //If the btSocket is busy
        {
            try
            {
                btSocket.close(); //close connection
            }
            catch (IOException e)
            { msg("Error");}
        }
        finish(); //return to the first layout

    }

    private void turnOffLed()
    {
        if (btSocket!=null)
        {
            try
            {
                btSocket.getOutputStream().write("TF".toString().getBytes());
            }
            catch (IOException e)
            {
                msg("Error");
            }
        }
    }

    private void turnOnLed()
    {
        if (btSocket!=null)
        {
            try
            {
                btSocket.getOutputStream().write("TO".toString().getBytes());
            }
            catch (IOException e)
            {
                msg("Error");
            }
        }
    }

    private void receives() {

        try {
            int bytes = 0, offset = 0;
            byte[] buffer;
            inputStream = btSocket.getInputStream();
            bytes = inputStream.read();
            buffer = new byte[bytes];
            while (true)
            {
                bytes = inputStream.read(buffer, offset, buffer.length - offset);
                offset += bytes;
                if (bytes == -1 || offset >= buffer.length)
                {
                    Log.d("MyBT", "message: " + new String(buffer));
                    testings.setText(new String(buffer));
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // fast way to call Toast
    private void msg(String s)
    {
        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
    }

    private class ConnectBT extends AsyncTask<Void, Void, Void>  // UI thread
    {
        private boolean ConnectSuccess = true; //if it's here, it's almost connected

        @Override
        protected void onPreExecute()
        {
            progress = ProgressDialog.show(Menu.this, "Connecting...", "Please wait!!!");  //show a progress dialog
        }

        @Override
        protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
        {
            try
            {
                if (btSocket == null || !isBtConnected)
                {
                    myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                    BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
                    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    btSocket.connect();//start connection
                }
            }
            catch (IOException e)
            {
                ConnectSuccess = false;//if the try failed, you can check the exception here
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
        {
            super.onPostExecute(result);

            if (!ConnectSuccess)
            {
                msg("Connection Failed. Try again.");
                finish();
            }
            else
            {
                msg("Connected.");
                isBtConnected = true;
            }
            progress.dismiss();
        }
    }
}

我想连续运行的方法:

private void receives() {

        try {
            int bytes = 0, offset = 0;
            byte[] buffer;
            inputStream = btSocket.getInputStream();
            bytes = inputStream.read();
            buffer = new byte[bytes];
            while (true)
            {
                bytes = inputStream.read(buffer, offset, buffer.length - offset);
                offset += bytes;
                if (bytes == -1 || offset >= buffer.length)
                {
                    Log.d("MyBT", "message: " + new String(buffer));
                    testings.setText(new String(buffer));
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

stacktrace错误:

03-03 08:35:44.280 10854-12219/com.example.android.cigarettebox E/AndroidRuntime: FATAL EXCEPTION: Thread-7962
                                                                                  Process: com.example.android.cigarettebox, PID: 10854
                                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStream android.bluetooth.BluetoothSocket.getInputStream()' on a null object reference
                                                                                      at com.example.android.cigarettebox.Menu$MyThread.run(Menu.java:254)
03-03 08:35:44.296 10854-12218/com.example.android.cigarettebox W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
03-03 08:35:44.676 10854-10861/com.example.android.cigarettebox W/art: Suspending all threads took: 6.314ms
03-03 08:35:44.820 10854-11128/com.example.android.cigarettebox D/OpenGLRenderer: endAllStagingAnimators on 0xb39e4e00 (ListView) with handle 0xa1108a60
03-03 08:35:45.260 10854-10854/com.example.android.cigarettebox E/WindowManager: android.view.WindowLeaked: Activity com.example.android.cigarettebox.Menu has leaked window com.android.internal.policy.PhoneWindow$DecorView{3cd38ff V.E...... R......D 0,0-1026,483} that was originally added here
                                                                                     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:368)
                                                                                     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
                                                                                     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                                     at android.app.Dialog.show(Dialog.java:319)
                                                                                     at android.app.ProgressDialog.show(ProgressDialog.java:116)
                                                                                     at android.app.ProgressDialog.show(ProgressDialog.java:99)
                                                                                     at android.app.ProgressDialog.show(ProgressDialog.java:94)
                                                                                     at com.example.android.cigarettebox.Menu$ConnectBT.onPreExecute(Menu.java:200)
                                                                                     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
                                                                                     at android.os.AsyncTask.execute(AsyncTask.java:551)
                                                                                     at com.example.android.cigarettebox.Menu.onCreate(Menu.java:61)
                                                                                     at android.app.Activity.performCreate(Activity.java:6251)
                                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

您可以使用普通的Java thread进行操作。

 class MyThread extends Thread {
     Socket btSocket;
     PrimeThread(Socket btSocket) {
         this.btSocket = btSocket;
     }

     public void run() {
         // your socket stuff
          . . .
     }
 }