我是java编程的全新手,我的应用程序到目前为止一直工作,我找不到错误的原因。应用程序立即打开时关闭(强制关闭)。提前致谢!
logcat的:
09-02 01:07:15.932 15469-15469/com.example.yusuf.bluetoothserver I/art: Late-enabling -Xcheck:jni
09-02 01:07:15.959 15469-15469/com.example.yusuf.bluetoothserver W/System: ClassLoader referenced unknown path: /data/app/com.example.yusuf.bluetoothserver-2/lib/arm
09-02 01:07:16.011 15469-15469/com.example.yusuf.bluetoothserver W/System: ClassLoader referenced unknown path: /data/app/com.example.yusuf.bluetoothserver-2/lib/arm
09-02 01:07:16.046 15469-15469/com.example.yusuf.bluetoothserver W/Xposed: Package name for /data/data/com.example.yusuf.bluetoothserver/files/instant-run/left/resources.ap_ had to be retrieved via parser
09-02 01:07:16.081 15469-15469/com.example.yusuf.bluetoothserver V/UUID: 52e2e4ec-0541-4e5e-b599-467ee6fec3aa
09-02 01:07:16.084 15469-15469/com.example.yusuf.bluetoothserver D/AndroidRuntime: Shutting down VM
09-02 01:07:16.085 15469-15469/com.example.yusuf.bluetoothserver E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yusuf.bluetoothserver, PID: 15469
Theme: themes:{}
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/content/ContextCompat;
at com.example.yusuf.bluetoothserver.MainActivity.requestPermission(MainActivity.java:606)
at com.example.yusuf.bluetoothserver.MainActivity.onCreate(MainActivity.java:122)
at android.app.Activity.performCreate(Activity.java:7125)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.ContextCompat" on path: DexPathList[[dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-internal_impl-23.1.1_97e3b4268259621b3c54683f9e2f54c902b84549-classes.dex"],nativeLibraryDirectories=[/data/app/com.example.yusuf.bluetoothserver-2/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoader.findClass(IncrementalClassLoader.java:90)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at com.example.yusuf.bluetoothserver.MainActivity.requestPermission(MainActivity.java:606)
at com.example.yusuf.bluetoothserver.MainActivity.onCreate(MainActivity.java:122)
at android.app.Activity.performCreate(Activity.java:7125)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
Suppressed: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.ContextCompat" on path: DexPathList[[zip file "/data/app/com.example.yusuf.bluetoothserver-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.yusuf.bluetoothserver-2/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 16 more
Suppressed: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.ContextCompat" on path: DexPathList[[dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.example.yusuf.bluetoothserver/files/instant-run/dex/slice-internal_impl-23.1.1_97e3b4268259621b3c54683f9e2f54c902b84549-classes.dex"],nativeLibraryDirectories=[/data/app/com.example.yusuf.bluetoothserver-2/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoader.findClass(IncrementalClassLoader.java:90)
at com.android.tools.fd.runtime.IncrementalClassLoader.findClass(IncrementalClassLoader.java:62)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 17 more
Suppressed: java.lang.ClassNotFoundException: android.support.v4.content.ContextCompat
at java.lang.Class.classForName(Native Method)
代码(丑陋,我知道):
(我已经删除了导入的东西,因为身体限制字符不会让我发帖)
public class MainActivity extends Activity {
BluetoothAdapter bluetoothAdapter;
ListView listView;
ArrayAdapter<String> arrayAdapter;
static final int Permission_Req_Code = 1;
Button pairBtn;
Button discoverBtn;
ToggleButton discoverToggle;
boolean isRegistered;
boolean btExitSetting;
boolean inSettings;
boolean serverListening;
RadioGroup radioGroup;
RadioButton receiveRadioBtn;
RadioButton sendRadioBtn;
EditText userInputField;
String userInput = "";
String clientMsg;
// Button receiveBtn = (Button) findViewById(R.id.receiveBtn);
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Log.v("UUID",String.valueOf(UUID.randomUUID()));
/* ___ Setting Up Bluetooth ___ */
// - Get the BluetoothAdapter -
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
////BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(BLUETOOTH_SERVICE);
////bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
Toast noBT_toast = Toast.makeText(this,"Device does not support Bluetooth!",Toast.LENGTH_SHORT);
noBT_toast.show();
}
// - Enable Bluetooth -
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
}
listView = (ListView)findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
listView.setAdapter(arrayAdapter);
// * As of Marshmallow, permissions that are not considered "normal" (dangerous - may expose user data), must be granted by user at runtime.
// This includes starting bluetooth discovery feature.
// Request Location Permission (needed for Bluetooth) at RunTime:
requestPermission();
pairBtn = (Button)findViewById(R.id.pairBtn);
pairBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ___ Finding paired devices ___ //
pairedDevices();
}
});
discoverToggle = (ToggleButton)findViewById(R.id.discoverToggle);
discoverToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
discoverDevices();
}
else if (!isChecked) {
disableDiscovery();
}
}
});
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
receiveRadioBtn = (RadioButton) findViewById(R.id.receiveRadioBtn);
sendRadioBtn = (RadioButton) findViewById(R.id.sendRadioBtn);
// userInputField = (EditText) findViewById(R.id.userInputField);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
View view = menu.findItem(R.id.action_connect).getActionView();
Switch connect_switch = (Switch) view.findViewById(R.id.connect_switch);
connect_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
AcceptThread acceptThread = new AcceptThread();
if (isChecked) {
Log.d("Switch", "Checked");
acceptThread.start();
}
else if (!isChecked) {
Log.d("Switch", "!Checked");
acceptThread.closeConnection();
}
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.action_settings) {
Intent settingIntent = new Intent(this, Settings.class);
startActivity(settingIntent);
inSettings = true;
}
if (item.getItemId() == R.id.action_exit) {
onStop();
finish();
}
return true;
}
@Override
protected void onResume() {
super.onResume();
if (getIntent().getExtras() != null) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
btExitSetting = sharedPref.getBoolean("pref_key_exit_bluetooth", false);
Log.v("Bundle", String.valueOf(btExitSetting));
inSettings = false;
}
}
@Override
protected void onStop() {
super.onStop();
Log.w("onStop", "invoked!");
disableDiscovery();
if (btExitSetting && !inSettings) {
bluetoothAdapter.disable();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.w("onDestroy", "invoked!");
}
/* ___ Finding paired devices ___ */
private void pairedDevices() {
// - Querying paired devices -
final Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
// - Discovering devices -
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("onReceive","Invoked");
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.v("BT Devices","Found");
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
Log.e("BT", device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
}
else {
Log.v("BT Devices","!!!Found");
}
isRegistered = true;
}
};
private void discoverDevices() {
// - Enabling discoverability -
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// * Add following actions to ensure the start of the BT dicovery mode.
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(broadcastReceiver, filter); // Don't forget to unregister during onDestroy
if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
if (bluetoothAdapter != null) {
Log.e("adapter","Not Null!");
}
bluetoothAdapter.startDiscovery();
if (bluetoothAdapter.isDiscovering()) {
Log.e("BTadapter","Discovering!");
}
}
private void disableDiscovery() {
bluetoothAdapter.cancelDiscovery();
if (isRegistered) {
unregisterReceiver(broadcastReceiver);
}
}
/* ___ Accepting Client Connection. ___*/
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
ConnectedThread connectedThread;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
String NAME = "BluetoothServer";
UUID MY_UUID = UUID.fromString("0ae3d869-470e-45d1-b147-a10882fc1bd2");
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
Log.e("Server", "Listening");
}
catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
Log.e("Connection","Accepted");
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
connectedThread = new ConnectedThread(socket);
connectedThread.start();
cancel();
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
public void closeConnection() {
if (connectedThread != null) {
connectedThread.close();
}
}
}
/* Managing Connection */
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
BufferedReader inputStream;
PrintWriter outputStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputStream = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
RadioButton rb = (RadioButton) findViewById(R.id.receiveRadioBtn);
rb.setOnClickListener(new RadioButton.OnClickListener(){
@Override
public void onClick(View v)
/*{ Synchro Sync = new Synchro();
Thread t = new Thread(Sync);
t.start();}*/
{
for(int i = 0; i < 1000; i++) {
read();
TextView clientMsgTxV = (TextView) findViewById(R.id.clientMsgTxV);
clientMsgTxV.setText(clientMsg);
Log.i("Server MSG", clientMsg);
}
}
});
final ToggleButton receiveBtn = (ToggleButton) findViewById(R.id.receiveBtn);
receiveBtn.setOnClickListener(new ToggleButton.OnClickListener(){
@Override
public void onClick(View v) {
while (true) {
try {
if (mmInStream.available() > 0 ){
read();
TextView clientMsgTxV = (TextView) findViewById(R.id.clientMsgTxV);
clientMsgTxV.setText(clientMsg);
Log.i("Server MSG", clientMsg);
}
else SystemClock.sleep(100);
}
catch(IOException Io)
{
close();
break;
}
}
}
});
}
private void read() {
try {
if(inputStream.ready()) {
if ((clientMsg = inputStream.readLine()) != null || !("".equals(clientMsg))) {
} else {
clientMsg = "empty";
}
Log.i("Server MSG", clientMsg);
Log.v("InputStream", "Read");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void write() {
// To ensure that the User Input is added to the output stream - add a conditional statement to check if userInput variable is not null.
if (userInput != null) {
Log.e("User Input", userInput);
outputStream.println(userInput);
Log.d("Output Stream", "Written to Client");
}
}
/* Shutdown the connection */
public void close() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void requestPermission() {
// Here, this is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
Permission_Req_Code);
// Permission_Req_Code is an app-defined int constant.
// The callback method gets the result of the request.
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case Permission_Req_Code: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted - Do the BT-related task you need to do.
} else {
// permission denied - Disable the functionality that depends on this permission.
String btPermissionDeniedStr = "Sorry, Bluetooth communication is not possible without granting location permission";
Toast.makeText(this,btPermissionDeniedStr,Toast.LENGTH_LONG).show();
}
return;
}
}
}
public void setReToText() {
TextView clientMsgTxV = (TextView) findViewById(R.id.clientMsgTxV);
clientMsgTxV.setText(clientMsg);
Log.i("Server MSG", clientMsg);
}
}
答案 0 :(得分:0)
您似乎错过了支持库。你可以发布app模块和项目的build.gradle文件吗?