2016-12-29 80 views
0

我是新來的Java編程,我有一個問題。我在使用藍牙的arduino汽車的控制器工作。該車有3個runnig模式:測試,汽車手冊。我做了一個MainActivity,它有一個佈局,每個模式有3個按鈕,一個按鈕連接用於藍牙連接。在另一個活動SecondActivity,有另一種佈局與控制汽車的方向和速度的按鈕,但出人意料地mBluetooth.write不起作用。如何在其他活動中使用藍牙傳輸數據?

這是在MainActivity:

public class MainActivity extends AppCompatActivity { 

ImageButton test, manual,connect; 
Button back; 

private BluetoothAdapter mbluetoothAdapter; 
protected AlertDialog.Builder builder; 
ConnectThread mBluetooth = new ConnectThread(); 
String mBluetoothName = ""; 
String mBluetoothAdress = ""; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    final Context context = this; 
    //final LayoutInflater factory = getLayoutInflater(); 
    //final View textEntryView = factory.inflate(R.layout.activity_main); 
    builder = new AlertDialog.Builder(this); 
    mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 


    connect = (ImageButton) findViewById(R.id.connect); 
    test = (ImageButton) findViewById(R.id.test); 
    manual = (ImageButton) findViewById(R.id.manual); 


    test.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(context,SecondActivity.class); 
      context.startActivity(intent); 
     } 

    }); 
    manual.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(context,SecondActivity.class); 
      context.startActivity(intent); 
     } 

    }); 
    connect.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if (!mbluetoothAdapter.isEnabled()) { 
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivity(enableBtIntent); 
      } else { 
       if (!mBluetooth.mBluetoothAddress.equals("")) {//if another connection is already exits then close it first 
        stopAllActivities(); 
       } else { 
        try { 
         Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class); 
         startActivityForResult(serverIntent, Helper.REQUEST_CONNECT_DEVICE); 
        } catch (Exception e) { 
         showToast(getString(R.string.errorOccured) + ": " + e.getMessage()); 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 
    }); 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case Helper.REQUEST_CONNECT_DEVICE: 
      if (resultCode == Activity.RESULT_OK) { 
       mBluetoothName = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_NAME); 
       mBluetoothAdress = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_ADDRESS); 

       // setBluetoothInfo(); 
       showToast(R.string.connectedDevice + mBluetoothName); 

       if (!mBluetoothAdress.equals("")) { 
        if (!mBluetooth.connect(mBluetoothAdress)){ 


        } 
       } 
      } 
      break; 
    } 
} 

private void showToast(String message) { 
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); 
} 

private void stopAllActivities() { 
    mBluetooth.write("S"); //send Stop Signal before it closes the connection 

    mBluetooth.mBluetoothAddress = ""; // reset address 
    mBluetooth.close();//close Connection 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    //getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onPause() { 
    if (mbluetoothAdapter != null) { 
     if (mbluetoothAdapter.isDiscovering()) { 
      mbluetoothAdapter.cancelDiscovery(); 
     } 
    } 
    super.onPause(); 
}} 

這是SecondActivity:

public class SecondActivity extends AppCompatActivity { 
final Context context = this; 
Button back; 
ImageButton btnup, btndown, btnright, btnleft; 
ConnectThread mBluetooth = new ConnectThread();//?????? 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    back = (Button) findViewById(R.id.back); 
    back.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(context, MainActivity.class); 
      context.startActivity(intent); 
     } 

    }); 

    btnup = (ImageButton) findViewById(R.id.btnup); 
    btndown = (ImageButton) findViewById(R.id.btndown); 
    btnleft = (ImageButton) findViewById(R.id.btnleft); 
    btnright = (ImageButton) findViewById(R.id.btnright); 
    final TextView direction = (TextView) findViewById(R.id.text_direction); 
    final TextView steering = (TextView) findViewById(R.id.steering_direction); 
    final Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer); 

    btndown.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("2"); 
       direction.setText(R.string.Backwards); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("x"); 
       direction.setText(R.string.blank); 
      } 


      return false; 

     } 
    }); 
    btnup.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("8"); 
       direction.setText(R.string.Forward); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("z"); 
       direction.setText(R.string.blank); 
      } 


      return false; 

     } 
    }); 

    btnright.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("6"); 
       steering.setText(R.string.Right); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("c"); 
       steering.setText(R.string.none); 
      } 


      return false; 

     } 
    }); 
    btnleft.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("4"); 
       steering.setText(R.string.Left); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("v"); 
       steering.setText(R.string.none); 
      } 


      return false; 

     } 
    }); 


}} 

我測試了藍牙連接和代碼按鈕在一個活動和工作的罰款

回答

0

這可能做一個鍛鍊。 在MainActivity中使ConnectThread實例mBluetooth爲靜態。現在,它將充當類字段,並將保留其實例直到應用程序的整個生命週期。

下面是代碼:

MainActivity.java

public class MainActivity extends AppCompatActivity { 

ImageButton test, manual,connect; 
Button back; 

private BluetoothAdapter mbluetoothAdapter; 
protected AlertDialog.Builder builder; 
//Static instance declaration 
public static ConnectThread mBluetooth; 
String mBluetoothName = ""; 
String mBluetoothAdress = ""; 

//Static block to initialise static instance 
static{ 
    mBluetooth=new ConnectThread(); 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    final Context context = this; 
    //final LayoutInflater factory = getLayoutInflater(); 
    //final View textEntryView = factory.inflate(R.layout.activity_main); 
    builder = new AlertDialog.Builder(this); 
    mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 


    connect = (ImageButton) findViewById(R.id.connect); 
    test = (ImageButton) findViewById(R.id.test); 
    manual = (ImageButton) findViewById(R.id.manual); 


    test.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(context,SecondActivity.class); 
      context.startActivity(intent); 
     } 

    }); 
    manual.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(context,SecondActivity.class); 
      context.startActivity(intent); 
     } 

    }); 
    connect.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if (!mbluetoothAdapter.isEnabled()) { 
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivity(enableBtIntent); 
      } else { 
       if (!mBluetooth.mBluetoothAddress.equals("")) {//if another connection is already exits then close it first 
        stopAllActivities(); 
       } else { 
        try { 
         Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class); 
         startActivityForResult(serverIntent, Helper.REQUEST_CONNECT_DEVICE); 
        } catch (Exception e) { 
         showToast(getString(R.string.errorOccured) + ": " + e.getMessage()); 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 
    }); 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case Helper.REQUEST_CONNECT_DEVICE: 
      if (resultCode == Activity.RESULT_OK) { 
       mBluetoothName = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_NAME); 
       mBluetoothAdress = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_ADDRESS); 

       // setBluetoothInfo(); 
       showToast(R.string.connectedDevice + mBluetoothName); 

       if (!mBluetoothAdress.equals("")) { 
        if (!mBluetooth.connect(mBluetoothAdress)){ 


        } 
       } 
      } 
      break; 
    } 
} 

private void showToast(String message) { 
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); 
} 

private void stopAllActivities() { 
    mBluetooth.write("S"); //send Stop Signal before it closes the connection 

    mBluetooth.mBluetoothAddress = ""; // reset address 
    mBluetooth.close();//close Connection 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    //getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onPause() { 
    if (mbluetoothAdapter != null) { 
     if (mbluetoothAdapter.isDiscovering()) { 
      mbluetoothAdapter.cancelDiscovery(); 
     } 
    } 
    super.onPause(); 
}} 

SecondActivity.java

public class SecondActivity extends AppCompatActivity { 
final Context context = this; 
Button back; 
ImageButton btnup, btndown, btnright, btnleft; 
//Declare a static reference from MainActivity class 
ConnectThread mBluetooth = MainActivity.mBluetooth; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    back = (Button) findViewById(R.id.back); 
    back.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(context, MainActivity.class); 
      context.startActivity(intent); 
     } 

    }); 

    btnup = (ImageButton) findViewById(R.id.btnup); 
    btndown = (ImageButton) findViewById(R.id.btndown); 
    btnleft = (ImageButton) findViewById(R.id.btnleft); 
    btnright = (ImageButton) findViewById(R.id.btnright); 
    final TextView direction = (TextView) findViewById(R.id.text_direction); 
    final TextView steering = (TextView) findViewById(R.id.steering_direction); 
    final Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer); 

    btndown.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("2"); 
       direction.setText(R.string.Backwards); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("x"); 
       direction.setText(R.string.blank); 
      } 


      return false; 

     } 
    }); 
    btnup.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("8"); 
       direction.setText(R.string.Forward); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("z"); 
       direction.setText(R.string.blank); 
      } 


      return false; 

     } 
    }); 

    btnright.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("6"); 
       steering.setText(R.string.Right); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("c"); 
       steering.setText(R.string.none); 
      } 


      return false; 

     } 
    }); 
    btnleft.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       mBluetooth.write("4"); 
       steering.setText(R.string.Left); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       mBluetooth.write("v"); 
       steering.setText(R.string.none); 
      } 


      return false; 

     } 
    }); 


}} 

希望這有助於。祝你好運!

0

讀你的代碼,我在第二個活動中發現:

ConnectThread mBluetooth = new ConnectThread(); //?????? 

什麼意味着你正在創建另一個對象是中MainAvtivity創建不同的,所以這個新對象未連接。這就解釋了爲什麼如果你在同一個MainActivity中使用同一個對象,那麼這個方法的寫入就會起作用

我建議你讓這個對象靜態並在secondActivity中使用它。所以去除

ConnectThread mBluetooth = new ConnectThread(); //?????? 

使靜態mBluetooth對象MainActivity

Static ConnectThread mBluetooth = new ConnectThread(); 

,我們需要寫的東西在SecondActivity使用

MainAcivity.mBluetooth.write(data); 

不建議在所有使物體靜止的,而是如果它不是一個大應用程序是一個很好的解決方法。

希望這對你有所幫助!