首页 > 解决方案 > 有没有办法修复启动画面与代码的交互并避免崩溃?

问题描述

我正在使用 android studio 设置这个 android 蓝牙应用程序,但我无法让启动画面正确显示,然后使用程序进行转换。为了让我的主屏幕和启动屏幕一起工作而不会导致程序崩溃,我需要做什么?

我曾尝试操纵清单以使主 GUI 和启动屏幕一起工作,但通常只有其中一个工作,然后应用程序崩溃。我目前正在使用最新版本的 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)

 

/////////////////////////////////////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();
            }
        }
    }
}

标签: javaandroidsplash-screen

解决方案


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);

推荐阅读