我正在使用android studio设置此android蓝牙应用程序,但我无法使启动屏幕正确显示,然后再过渡到该程序。为了使我的主屏幕和启动屏幕能够一起工作而不会导致程序崩溃,该怎么办?
我尝试操纵清单以使主GUI和启动屏幕一起工作,但通常只有其中一个工作,随后应用程序崩溃。我目前正在使用最新版本的Android Studio,并多次修改了初始屏幕,但我认为主要问题与清单有关。
<?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>
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();
}
}
}
}
答案 0 :(得分:0)
我认为您应该更正您的应用程序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);
}
}
答案 1 :(得分:0)
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);
答案 2 :(得分:0)
您正在尝试通过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;
}