Android getIntent (). GetExtra () возвращает ноль - PullRequest
0 голосов
/ 11 мая 2018

Я создаю приложение Bluetooth, пытаюсь передать экземпляр класса BluetoothConnection (который содержит внутренние классы ConnectThread и ConnectedThread) между действиями. etIntgent () для BlindsActivity возвращает «BlindsActivity», а не фактическое родительское намерение. getParentActivityIntent (), кажется, работает, но вызывает getParentActivityIntent (). getExtra всегда возвращает ноль, даже для данных String.

Код из DeviceListActivity: (родительское действие)

открытый класс DeviceListActivity расширяет AppCompatActivity, реализует Serializable {

//widgets
ListView devicesView;

//Bluetooth
private BluetoothAdapter btAdapter;
private BluetoothDevice btDevice;
private Set<BluetoothDevice> setPairedDevices;
private ArrayList arrayListPairedDevices;
private BluetoothConnection btConnection;
public boolean connected;


@Override
protected void onCreate(Bundle savedInstanceState) {

    //set view
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);

    //call widgets
    devicesView = (ListView) findViewById(R.id.listViewDeviceList);

    //TEST
    String s = getIntent().getStringExtra("TEST");

    //check bluetooth is avaiable and on
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        displayMessage("Device doesn't support bluetooth");
        finish();
    }
    else if (!btAdapter.isEnabled()) {//if bluetooth is switched off request permission to turn on
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    }

    //get all paired devices
    arrayListPairedDevices = new ArrayList();
    setPairedDevices = btAdapter.getBondedDevices();//Set of all paired devices
    if (setPairedDevices.size() > 0) {
        //if there are paired devices, get name and MAC address of each
        for (BluetoothDevice dev : setPairedDevices){
            arrayListPairedDevices.add(dev.getName() + "\n" + dev.getAddress());
        }
    } else if(!btAdapter.isEnabled()) {
        displayMessage("Please enable Bluetooth before proceeding");
        finish();
    } else{
        displayMessage("No paired devices\nPair with relevant device before proceeding");
        finish();
    }

    //display bluetooth devices
    final ArrayAdapter arrAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayListPairedDevices);
    devicesView.setAdapter(arrAdapter);
    devicesView.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked

}

private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() {//make listView items clickable
    public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
        //get the device MAC address, the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);
        btDevice = btAdapter.getRemoteDevice(address);//create new device with chosen address

        //CONNECTION HAPPENS HERE

        btConnection = new BluetoothConnection(btDevice);


        if(btConnection.connect()){
            //if connection success
            Intent intent = new Intent(DeviceListActivity.this, BlindsActivity.class);
            intent.putExtra("TEST", "test");
            intent.putExtra("CONNECTION", (Serializable) btConnection);

            startActivity(intent);
        }
        else{
            displayMessage("Error connecting - please try again");
        }
    }
};


private void displayMessage(String s) {
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}

Соответствующий фрагмент кода от BlindsActivity: (ребенок / приемная деятельность) ПРИМЕЧАНИЕ getParentActivityIntent () возвращает здесь правильное намерение, но getIntent () - нет.

BluetoothConnection btConnection и String s равны нулю

public class BlindsActivity extends AppCompatActivity implements  Serializable {

    //widgets
    private Button btnProgram, btnOpen, btnClose, btn34Open, btn34Close, btnCustom, btnSetup, btnSubmit, btnDisconnect;
    private TextView txtViewConnected;

    @Override
    protected void onNewIntent(Intent intent){
        super.onNewIntent(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //set view
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blinds);

        //call widgets
        btnProgram = (Button) findViewById(R.id.btnProgram);
        btnOpen = (Button) findViewById(R.id.btnOpen);
        btnClose = (Button) findViewById(R.id.btnClose);
        btn34Open = (Button) findViewById(R.id.btn34Open);
        btn34Close = (Button) findViewById(R.id.btn34Closed);
        btnCustom = (Button) findViewById(R.id.btnCustom);
        btnSetup = (Button) findViewById(R.id.btnSetUp);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnDisconnect = (Button) findViewById(R.id.btnDisconnect);

        //set action bar title
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Blinds");


        //receive instance of BluetoothConnection from previous activity
        Intent i = getParentActivityIntent();
        String s = i.getStringExtra("TEST");
        BluetoothConnection btConnection = (BluetoothConnection) i.getSerializableExtra("CONNECTION");

        //get instance of ConnectedThread from BluetoothActivity
        final BluetoothConnection.ConnectedThread connectedThread = btConnection.connectedThread;

Класс BluetoothConnection:

public class BluetoothConnection implements Serializable {



    //Bluetooth
    private BluetoothDevice btDevice;
    public ConnectThread connectThread;
    public ConnectedThread connectedThread;
    private boolean connected;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    public BluetoothConnection (BluetoothDevice device){
        //constructor
        btDevice = device;
    }

    public boolean connect(){
        //initialises ConnectThread - done here for syncing with UI Thread and passing between activities
         connectThread = new ConnectThread(btDevice);
         connectThread.start();

         try{
             // sync threads to return only after the connection is created
             connectThread.join();
         } catch (InterruptedException e) {e.printStackTrace();}

         return connected;
    }



    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            byte[] writeBuf = (byte[]) msg.obj;
            int begin = (int)msg.arg1;
            int end = (int)msg.arg2;

            switch(msg.what){
                case 1:
                    String writeMessage = new String(writeBuf);
                    writeMessage = writeMessage.substring(begin, end);
                    break;
            }
        }
    };



    public class ConnectThread extends Thread implements Serializable{

        public final BluetoothSocket btSocket;

        public ConnectThread(BluetoothDevice btDevice){
            //constructor

            BluetoothSocket tmpSocket = null;
            try {//attempts to obtain and open a Bluetooth Socket, uses temp socket until confirmed working
                tmpSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {e.printStackTrace();}

            btSocket = tmpSocket;
        }

        public void run(){
            //attempts to connect socket to remote device
            try{
                btSocket.connect();
                connected = true;
            } catch (IOException e) {e.printStackTrace(); connected = false; return;}

            connectedThread = new ConnectedThread(btSocket);
            connectedThread.start();
        }

        public boolean disconnect(){
            try {
                btSocket.close();
            } catch (IOException e) {e.printStackTrace(); return false;}
            return true;
        }
    }//end class ConnectThread


    public class ConnectedThread extends Thread implements Serializable{

        private final InputStream inStream;
        private final OutputStream outStream;
        private final BluetoothSocket btSocket;

        public ConnectedThread(BluetoothSocket socket){
            //constructor

            btSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try{ //attempts to open input and output streams on socket
                tmpIn = btSocket.getInputStream();
                tmpOut = btSocket.getOutputStream();
            } catch (IOException e) {e.printStackTrace();}

            inStream = tmpIn;
            outStream = tmpOut;

        }

        public void run(){
            byte[] buffer = new byte[1024];
            int begin = 0;
            int bytes = 0;

            while (true){
                try{
                    bytes += inStream.read(buffer, bytes, buffer.length - bytes);
                    for (int i = begin; i < bytes; i++){
                        if (buffer[i] == "#".getBytes()[0]){
                            handler.obtainMessage(1, begin, i, buffer).sendToTarget();
                            begin = i+1;
                            if(i == (bytes - 1)){
                                bytes = begin = 0;
                            }
                        }
                    }
                } catch (IOException e) {e.printStackTrace(); break;}
            }

        }

        public void write(byte[] bytes){
            try{
                outStream.write(bytes);
            } catch (IOException e) {e.printStackTrace();}
        }

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


    }
}//END

А вот и мой AndroidManifest.xml

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:configChanges="orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".DeviceListActivity"
        android:configChanges="orientation"
        android:parentActivityName=".MainActivity"
        android:screenOrientation="portrait" />
    <activity
        android:name=".BlindsActivity"
        android:configChanges="orientation"
        android:parentActivityName=".DeviceListActivity"
        android:screenOrientation="portrait" />
    <activity
        android:name=".ProgramActivity"
        android:configChanges="orientation"
        android:parentActivityName=".BlindsActivity"
        android:screenOrientation="portrait" />
    <activity android:name=".SetUpActivity" />
</application>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...