Есть ли способ исправить взаимодействие заставки с кодом и избежать сбоев? - PullRequest
1 голос
/ 03 апреля 2019

Я настраиваю это Android-приложение Bluetooth с помощью Android Studio, и у меня возникают проблемы с корректным отображением заставки, а затем происходит переход с программой. Что мне нужно сделать, чтобы мой основной и заставки работали вместе без сбоев программы?

Я пытался манипулировать манифестом, чтобы заставить основной графический интерфейс и заставку работать вместе, но обычно работает только один из них, после чего происходит сбой приложения. В настоящее время я использую последнюю версию Android Studio и несколько раз пересматривал заставку, но считаю, что основная проблема связана с манифестом.

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.harbit">
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <application

        <activity android:name=".Splash"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
        <activity android:name=".BT">          </activity>
        <activity android:name=".BTGU">        </activity>
        <activity android:name=".REC" >        </activity>

    </application>
</manifest>

Java-код заставки

   package com.example.harbit;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Splash extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent Intent = new Intent(Splash.this, BTGU.class);
                startActivity(Intent);

            }
        },4000);

    }
}

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

2019-04-05 12:13:55.395 8028-8028/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.harbit, PID: 8028
    java.lang.RuntimeException: Unable to resume activity {com.example.harbit/com.example.harbit.BTGU}: java.lang.IllegalArgumentException: null is not a valid Bluetooth address
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3987)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4019)
        at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6981)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
     Caused by: java.lang.IllegalArgumentException: null is not a valid Bluetooth address
        at android.bluetooth.BluetoothDevice.<init>(BluetoothDevice.java:1176)
        at android.bluetooth.BluetoothAdapter.getRemoteDevice(BluetoothAdapter.java:917)
        at com.example.harbit.BTGU.onResume(BTGU.java:125)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1412)
        at android.app.Activity.performResume(Activity.java:7557)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3979)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4019) 
        at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:51) 
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:6981) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

1014 *

///////////////////////////////////////////// BTGU Деятельность //////////////////////////////

package com.example.harbit;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;

import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

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

public class BTGU extends AppCompatActivity {

    //1)
    ImageButton IdListen, IdRecord,IdFiles,IdDisconect;
    TextView IdBPM;
    //-------------------------------------------
    Handler bluetoothIn;
    final int handlerState = 0;
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder DataStringIN = new StringBuilder();
    private ConnectedThread MyConexionBT;
    // Unique identifier of service - SPP UUID
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    // String for MAC address
    private static String address = null;
    //-------------------------------------------

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_btgu);
        //Link buttons to on click listeners
        IdListen = (ImageButton) findViewById(R.id.IdListen);
        IdRecord = (ImageButton) findViewById(R.id.IdRecord);
        IdFiles = (ImageButton) findViewById(R.id.IdFiles);
        IdDisconect = (ImageButton) findViewById(R.id.IdDisconect);
        IdBPM = (TextView) findViewById(R.id.IdBPM);

        bluetoothIn = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg.what == handlerState) {
                    String readMessage = (String) msg.obj;
                    DataStringIN.append(readMessage);

                    int endOfLineIndex = DataStringIN.indexOf("#");

                    if (endOfLineIndex > 0) {
                        String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
                        IdBPM.setText("BPM: " + dataInPrint);
                        DataStringIN.delete(0, DataStringIN.length());
                    }
                }
            }
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
        VerifyBT();

        // setup onClick listeners for the buttons
        // to indicate the following active after activation
        // of the onclick event
        // as an RXTX event
        IdListen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v)
            {
                MyConexionBT.write("1");
            }
        });

        IdRecord.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                MyConexionBT.write("2");
            }
        });

        IdFiles.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v)
            {
              //----------------------------------------------------------------------------------------------------->>>>>>
            }
        });

        IdDisconect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (btSocket!=null)
                {
                    try {btSocket.close();}
                    catch (IOException e)
                    { Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();;}
                }
                finish();
            }
        });
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
    {
        //Safe exit removal of the device
        //using service UUID
        return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        //get the MAC address from DeviceListActivity via intent
        Intent intent = getIntent();
        //get the MAC address from DeviceListActivity via EXTRA
        address = intent.getStringExtra(BT.EXTRA_DEVICE_ADDRESS);
        //Set the MAC address
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        try
        {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
        }
        // establish connection with Bluetooth socket.
        try
        {
            btSocket.connect();
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {}
        }
        MyConexionBT = new ConnectedThread(btSocket);
        MyConexionBT.start();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        try
        { // when out of the app this allows for the closing of the socket
            btSocket.close();
        } catch (IOException e2) {}
    }

    //check the device bluetooth and if off pop a message to turn it on
    private void VerifyBT() {

        if(btAdapter==null) {
            Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_LONG).show();
        } else {
            if (btAdapter.isEnabled()) {
            } else {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    //Create the class that enables the event of connectivity
    private class ConnectedThread extends Thread
    {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket)
        {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try
            {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
// set up Rx for incoming data
        public void run()
        {
            byte[] buffer = new byte[256];
            int bytes;

            // Begin listen mode to determine the incoming data
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);
                    String readMessage = new String(buffer, 0, bytes);
                    // Send the obtained data to the event via handler
                    bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }
        //String TX to the receiving device
        public void write(String input)
        {
            try {
                mmOutStream.write(input.getBytes());
            }
            catch (IOException e)
            {
                //If TX not available close connectivity
                Toast.makeText(getBaseContext(), "Connection failed", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}

Ответы [ 3 ]

0 голосов
/ 07 апреля 2019
Caused by: java.lang.IllegalArgumentException: null is not a valid Bluetooth address
        at android.bluetooth.BluetoothDevice.<init>(BluetoothDevice.java:1176)
        at android.bluetooth.BluetoothAdapter.getRemoteDevice(BluetoothAdapter.java:917)
        at com.example.harbit.BTGU.onResume(BTGU.java:125)

Вы получаете дополнительный бонус, который не был передан из предыдущего действия

        //This is null you never add the extra on the Splash
        address = intent.getStringExtra(BT.EXTRA_DEVICE_ADDRESS);
         //This is crashing, the address is null
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

В SplashActivity вам нужно

Intent Intent = new Intent(Splash.this, BTGU.class);
//I dont know how you plan to obatained the address
intent.putExtra(BT.EXTRA_DEVICE_ADDRESS, "A VALID ADDRESS");
startActivity(Intent);
0 голосов
/ 08 апреля 2019

Вы пытаетесь получить дополнительные данные с помощью намерения в операции BTGU, но не отправили его из операции SplashActivity.Вы должны добавить следующий код в SplashActivity.

Intent intent = new Intent(Splash.this, BTGU.class);
intent.putExtra(BT.EXTRA_DEVICE_ADDRESS, getMacAddress());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
              | Intent.FLAG_ACTIVITY_CLEAR_TASK 
              | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

Вы можете получить MAC-адрес с помощью следующего метода или попробовать свой собственный метод, чтобы получить Mac-адрес:

private String getMacAddress(){
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    String bluetoothMacAddress = "";
    try {
        Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
        mServiceField.setAccessible(true);

        Object btManagerService = mServiceField.get(bluetoothAdapter);

        if (btManagerService != null) {
            bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
        }
    } catch (NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignore) {

    }
    return bluetoothMacAddress;
}
0 голосов
/ 04 апреля 2019

Я думаю, что вы должны исправить файл AndroidManifest вашего приложения.Это может быть следующее:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.harbit">

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

 <application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <activity
        android:name=".Splash"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".BTGU"/>
    <activity android:name=".BTGU"/>
    <activity android:name=".REC"/>

  </application>
</manifest> 

И ваша всплывающая активность может быть:

package com.example.harbit;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Splash extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(Splash.this, BTGU.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
                  | Intent.FLAG_ACTIVITY_CLEAR_TASK 
                  | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    },4000);

  }
}
...