├── .gitignore ├── LICENSE.txt ├── README.md ├── app ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── de │ │ └── kai_morich │ │ └── simple_bluetooth_terminal │ │ ├── BluetoothUtil.java │ │ ├── Constants.java │ │ ├── DevicesFragment.java │ │ ├── MainActivity.java │ │ ├── SerialListener.java │ │ ├── SerialService.java │ │ ├── SerialSocket.java │ │ ├── TerminalFragment.java │ │ └── TextUtil.java │ └── res │ ├── drawable-hdpi │ ├── ic_clear_white_24dp.png │ └── ic_notification.png │ ├── drawable-mdpi │ ├── ic_clear_white_24dp.png │ └── ic_notification.png │ ├── drawable-xhdpi │ ├── ic_clear_white_24dp.png │ └── ic_notification.png │ ├── drawable-xxhdpi │ ├── ic_clear_white_24dp.png │ └── ic_notification.png │ ├── drawable-xxxhdpi │ ├── ic_clear_white_24dp.png │ └── ic_notification.png │ ├── drawable │ ├── ic_delete_white_24dp.xml │ └── ic_send_white_24dp.xml │ ├── layout │ ├── activity_main.xml │ ├── device_list_header.xml │ ├── device_list_item.xml │ └── fragment_terminal.xml │ ├── menu │ ├── menu_devices.xml │ └── menu_terminal.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ └── values │ ├── arrays.xml │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | /.gradle/ 3 | /.idea/ 4 | /local.properties 5 | /app/build/ 6 | /build/ 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Kai Morich 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a3d8a40d7133497caa11051eaac6f1a2)](https://www.codacy.com/manual/kai-morich/SimpleBluetoothTerminal?utm_source=github.com&utm_medium=referral&utm_content=kai-morich/SimpleBluetoothTerminal&utm_campaign=Badge_Grade) 2 | 3 | # SimpleBluetoothTerminal 4 | 5 | This Android app provides a line-oriented terminal / console for classic Bluetooth (2.x) devices implementing the Bluetooth Serial Port Profile (SPP) 6 | 7 | For an overview on Android Bluetooth communication see 8 | [Android Bluetooth Overview](https://developer.android.com/guide/topics/connectivity/bluetooth). 9 | 10 | This App implements RFCOMM connection to the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB 11 | 12 | ## Motivation 13 | 14 | I got various requests asking for help with Android development or source code for my 15 | [Serial Bluetooth Terminal](https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal) app. 16 | Here you find a simplified version of my app. 17 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdk 34 5 | defaultConfig { 6 | targetSdk 34 7 | minSdk 18 8 | vectorDrawables.useSupportLibrary true 9 | 10 | applicationId "de.kai_morich.simple_bluetooth_terminal" 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | compileOptions { 15 | sourceCompatibility JavaVersion.VERSION_1_8 16 | targetCompatibility JavaVersion.VERSION_1_8 17 | } 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | namespace 'de.kai_morich.simple_bluetooth_terminal' 25 | } 26 | 27 | dependencies { 28 | implementation 'androidx.appcompat:appcompat:1.6.1' 29 | implementation 'com.google.android.material:material:1.11.0' 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 21 | 25 | 26 | 27 | 28 | 29 | 30 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/BluetoothUtil.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.Manifest; 4 | import android.annotation.SuppressLint; 5 | import android.app.AlertDialog; 6 | import android.bluetooth.BluetoothDevice; 7 | import android.content.DialogInterface; 8 | import android.content.Intent; 9 | import android.content.pm.PackageManager; 10 | import android.net.Uri; 11 | import android.os.Build; 12 | 13 | import androidx.activity.result.ActivityResultLauncher; 14 | import androidx.fragment.app.Fragment; 15 | 16 | public class BluetoothUtil { 17 | 18 | interface PermissionGrantedCallback { 19 | void call(); 20 | } 21 | 22 | /** 23 | * sort by name, then address. sort named devices first 24 | */ 25 | @SuppressLint("MissingPermission") 26 | static int compareTo(BluetoothDevice a, BluetoothDevice b) { 27 | boolean aValid = a.getName()!=null && !a.getName().isEmpty(); 28 | boolean bValid = b.getName()!=null && !b.getName().isEmpty(); 29 | if(aValid && bValid) { 30 | int ret = a.getName().compareTo(b.getName()); 31 | if (ret != 0) return ret; 32 | return a.getAddress().compareTo(b.getAddress()); 33 | } 34 | if(aValid) return -1; 35 | if(bValid) return +1; 36 | return a.getAddress().compareTo(b.getAddress()); 37 | } 38 | 39 | /** 40 | * Android 12 permission handling 41 | */ 42 | private static void showRationaleDialog(Fragment fragment, DialogInterface.OnClickListener listener) { 43 | final AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getActivity()); 44 | builder.setTitle(fragment.getString(R.string.bluetooth_permission_title)); 45 | builder.setMessage(fragment.getString(R.string.bluetooth_permission_grant)); 46 | builder.setNegativeButton("Cancel", null); 47 | builder.setPositiveButton("Continue", listener); 48 | builder.show(); 49 | } 50 | 51 | private static void showSettingsDialog(Fragment fragment) { 52 | String s = fragment.getResources().getString(fragment.getResources().getIdentifier("@android:string/permgrouplab_nearby_devices", null, null)); 53 | final AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getActivity()); 54 | builder.setTitle(fragment.getString(R.string.bluetooth_permission_title)); 55 | builder.setMessage(String.format(fragment.getString(R.string.bluetooth_permission_denied), s)); 56 | builder.setNegativeButton("Cancel", null); 57 | builder.setPositiveButton("Settings", (dialog, which) -> 58 | fragment.startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, 59 | Uri.parse("package:" + BuildConfig.APPLICATION_ID)))); 60 | builder.show(); 61 | } 62 | 63 | static boolean hasPermissions(Fragment fragment, ActivityResultLauncher requestPermissionLauncher) { 64 | if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 65 | return true; 66 | boolean missingPermissions = fragment.getActivity().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED; 67 | boolean showRationale = fragment.shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_CONNECT); 68 | 69 | if(missingPermissions) { 70 | if (showRationale) { 71 | showRationaleDialog(fragment, (dialog, which) -> 72 | requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT)); 73 | } else { 74 | requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT); 75 | } 76 | return false; 77 | } else { 78 | return true; 79 | } 80 | } 81 | 82 | static void onPermissionsResult(Fragment fragment, boolean granted, PermissionGrantedCallback cb) { 83 | if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 84 | return; 85 | boolean showRationale = fragment.shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_CONNECT); 86 | if (granted) { 87 | cb.call(); 88 | } else if (showRationale) { 89 | showRationaleDialog(fragment, (dialog, which) -> cb.call()); 90 | } else { 91 | showSettingsDialog(fragment); 92 | } 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/Constants.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | class Constants { 4 | 5 | // values have to be globally unique 6 | static final String INTENT_ACTION_DISCONNECT = BuildConfig.APPLICATION_ID + ".Disconnect"; 7 | static final String NOTIFICATION_CHANNEL = BuildConfig.APPLICATION_ID + ".Channel"; 8 | static final String INTENT_CLASS_MAIN_ACTIVITY = BuildConfig.APPLICATION_ID + ".MainActivity"; 9 | 10 | // values have to be unique within each app 11 | static final int NOTIFY_MANAGER_START_FOREGROUND_SERVICE = 1001; 12 | 13 | private Constants() {} 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/DevicesFragment.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.Manifest; 4 | import android.annotation.SuppressLint; 5 | import android.bluetooth.BluetoothAdapter; 6 | import android.bluetooth.BluetoothDevice; 7 | import android.content.Intent; 8 | import android.content.pm.PackageManager; 9 | import android.os.Build; 10 | import android.os.Bundle; 11 | import android.view.Menu; 12 | import android.view.MenuInflater; 13 | import android.view.MenuItem; 14 | import android.view.View; 15 | import android.view.ViewGroup; 16 | import android.widget.ArrayAdapter; 17 | import android.widget.ListView; 18 | import android.widget.TextView; 19 | 20 | import androidx.activity.result.ActivityResultLauncher; 21 | import androidx.activity.result.contract.ActivityResultContracts; 22 | import androidx.annotation.NonNull; 23 | import androidx.fragment.app.Fragment; 24 | import androidx.fragment.app.ListFragment; 25 | 26 | import java.util.ArrayList; 27 | import java.util.Collections; 28 | 29 | public class DevicesFragment extends ListFragment { 30 | 31 | private BluetoothAdapter bluetoothAdapter; 32 | private final ArrayList listItems = new ArrayList<>(); 33 | private ArrayAdapter listAdapter; 34 | ActivityResultLauncher requestBluetoothPermissionLauncherForRefresh; 35 | private Menu menu; 36 | private boolean permissionMissing; 37 | 38 | @Override 39 | public void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | setHasOptionsMenu(true); 42 | if(getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) 43 | bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 44 | listAdapter = new ArrayAdapter(getActivity(), 0, listItems) { 45 | @NonNull 46 | @Override 47 | public View getView(int position, View view, @NonNull ViewGroup parent) { 48 | BluetoothDevice device = listItems.get(position); 49 | if (view == null) 50 | view = getActivity().getLayoutInflater().inflate(R.layout.device_list_item, parent, false); 51 | TextView text1 = view.findViewById(R.id.text1); 52 | TextView text2 = view.findViewById(R.id.text2); 53 | @SuppressLint("MissingPermission") String deviceName = device.getName(); 54 | text1.setText(deviceName); 55 | text2.setText(device.getAddress()); 56 | return view; 57 | } 58 | }; 59 | requestBluetoothPermissionLauncherForRefresh = registerForActivityResult( 60 | new ActivityResultContracts.RequestPermission(), 61 | granted -> BluetoothUtil.onPermissionsResult(this, granted, this::refresh)); 62 | } 63 | 64 | @Override 65 | public void onActivityCreated(Bundle savedInstanceState) { 66 | super.onActivityCreated(savedInstanceState); 67 | setListAdapter(null); 68 | View header = getActivity().getLayoutInflater().inflate(R.layout.device_list_header, null, false); 69 | getListView().addHeaderView(header, null, false); 70 | setEmptyText("initializing..."); 71 | ((TextView) getListView().getEmptyView()).setTextSize(18); 72 | setListAdapter(listAdapter); 73 | } 74 | 75 | @Override 76 | public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) { 77 | this.menu = menu; 78 | inflater.inflate(R.menu.menu_devices, menu); 79 | if(permissionMissing) 80 | menu.findItem(R.id.bt_refresh).setVisible(true); 81 | if(bluetoothAdapter == null) 82 | menu.findItem(R.id.bt_settings).setEnabled(false); 83 | } 84 | 85 | @Override 86 | public void onResume() { 87 | super.onResume(); 88 | refresh(); 89 | } 90 | 91 | @Override 92 | public boolean onOptionsItemSelected(MenuItem item) { 93 | int id = item.getItemId(); 94 | if (id == R.id.bt_settings) { 95 | Intent intent = new Intent(); 96 | intent.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); 97 | startActivity(intent); 98 | return true; 99 | } else if (id == R.id.bt_refresh) { 100 | if(BluetoothUtil.hasPermissions(this, requestBluetoothPermissionLauncherForRefresh)) 101 | refresh(); 102 | return true; 103 | } else { 104 | return super.onOptionsItemSelected(item); 105 | } 106 | } 107 | 108 | @SuppressLint("MissingPermission") 109 | void refresh() { 110 | listItems.clear(); 111 | if(bluetoothAdapter != null) { 112 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 113 | permissionMissing = getActivity().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED; 114 | if(menu != null && menu.findItem(R.id.bt_refresh) != null) 115 | menu.findItem(R.id.bt_refresh).setVisible(permissionMissing); 116 | } 117 | if(!permissionMissing) { 118 | for (BluetoothDevice device : bluetoothAdapter.getBondedDevices()) 119 | if (device.getType() != BluetoothDevice.DEVICE_TYPE_LE) 120 | listItems.add(device); 121 | Collections.sort(listItems, BluetoothUtil::compareTo); 122 | } 123 | } 124 | if(bluetoothAdapter == null) 125 | setEmptyText(""); 126 | else if(!bluetoothAdapter.isEnabled()) 127 | setEmptyText(""); 128 | else if(permissionMissing) 129 | setEmptyText(""); 130 | else 131 | setEmptyText(""); 132 | listAdapter.notifyDataSetChanged(); 133 | } 134 | 135 | @Override 136 | public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) { 137 | BluetoothDevice device = listItems.get(position-1); 138 | Bundle args = new Bundle(); 139 | args.putString("device", device.getAddress()); 140 | Fragment fragment = new TerminalFragment(); 141 | fragment.setArguments(args); 142 | getParentFragmentManager().beginTransaction().replace(R.id.fragment, fragment, "terminal").addToBackStack(null).commit(); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/MainActivity.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.os.Bundle; 4 | import androidx.fragment.app.FragmentManager; 5 | import androidx.appcompat.app.AppCompatActivity; 6 | import androidx.appcompat.widget.Toolbar; 7 | 8 | public class MainActivity extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener { 9 | 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.activity_main); 14 | Toolbar toolbar = findViewById(R.id.toolbar); 15 | setSupportActionBar(toolbar); 16 | getSupportFragmentManager().addOnBackStackChangedListener(this); 17 | if (savedInstanceState == null) 18 | getSupportFragmentManager().beginTransaction().add(R.id.fragment, new DevicesFragment(), "devices").commit(); 19 | else 20 | onBackStackChanged(); 21 | } 22 | 23 | @Override 24 | public void onBackStackChanged() { 25 | getSupportActionBar().setDisplayHomeAsUpEnabled(getSupportFragmentManager().getBackStackEntryCount()>0); 26 | } 27 | 28 | @Override 29 | public boolean onSupportNavigateUp() { 30 | onBackPressed(); 31 | return true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/SerialListener.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | interface SerialListener { 6 | void onSerialConnect (); 7 | void onSerialConnectError (Exception e); 8 | void onSerialRead (byte[] data); // socket -> service 9 | void onSerialRead (ArrayDeque datas); // service -> UI thread 10 | void onSerialIoError (Exception e); 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/SerialService.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.app.Notification; 4 | import android.app.NotificationChannel; 5 | import android.app.NotificationManager; 6 | import android.app.PendingIntent; 7 | import android.app.Service; 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.os.Binder; 11 | import android.os.Build; 12 | import android.os.Handler; 13 | import android.os.IBinder; 14 | import android.os.Looper; 15 | 16 | import androidx.annotation.Nullable; 17 | import androidx.annotation.RequiresApi; 18 | import androidx.core.app.NotificationCompat; 19 | 20 | import java.io.IOException; 21 | import java.util.ArrayDeque; 22 | 23 | /** 24 | * create notification and queue serial data while activity is not in the foreground 25 | * use listener chain: SerialSocket -> SerialService -> UI fragment 26 | */ 27 | public class SerialService extends Service implements SerialListener { 28 | 29 | class SerialBinder extends Binder { 30 | SerialService getService() { return SerialService.this; } 31 | } 32 | 33 | private enum QueueType {Connect, ConnectError, Read, IoError} 34 | 35 | private static class QueueItem { 36 | QueueType type; 37 | ArrayDeque datas; 38 | Exception e; 39 | 40 | QueueItem(QueueType type) { this.type=type; if(type==QueueType.Read) init(); } 41 | QueueItem(QueueType type, Exception e) { this.type=type; this.e=e; } 42 | QueueItem(QueueType type, ArrayDeque datas) { this.type=type; this.datas=datas; } 43 | 44 | void init() { datas = new ArrayDeque<>(); } 45 | void add(byte[] data) { datas.add(data); } 46 | } 47 | 48 | private final Handler mainLooper; 49 | private final IBinder binder; 50 | private final ArrayDeque queue1, queue2; 51 | private final QueueItem lastRead; 52 | 53 | private SerialSocket socket; 54 | private SerialListener listener; 55 | private boolean connected; 56 | 57 | /** 58 | * Lifecylce 59 | */ 60 | public SerialService() { 61 | mainLooper = new Handler(Looper.getMainLooper()); 62 | binder = new SerialBinder(); 63 | queue1 = new ArrayDeque<>(); 64 | queue2 = new ArrayDeque<>(); 65 | lastRead = new QueueItem(QueueType.Read); 66 | } 67 | 68 | @Override 69 | public void onDestroy() { 70 | cancelNotification(); 71 | disconnect(); 72 | super.onDestroy(); 73 | } 74 | 75 | @Nullable 76 | @Override 77 | public IBinder onBind(Intent intent) { 78 | return binder; 79 | } 80 | 81 | /** 82 | * Api 83 | */ 84 | public void connect(SerialSocket socket) throws IOException { 85 | socket.connect(this); 86 | this.socket = socket; 87 | connected = true; 88 | } 89 | 90 | public void disconnect() { 91 | connected = false; // ignore data,errors while disconnecting 92 | cancelNotification(); 93 | if(socket != null) { 94 | socket.disconnect(); 95 | socket = null; 96 | } 97 | } 98 | 99 | public void write(byte[] data) throws IOException { 100 | if(!connected) 101 | throw new IOException("not connected"); 102 | socket.write(data); 103 | } 104 | 105 | public void attach(SerialListener listener) { 106 | if(Looper.getMainLooper().getThread() != Thread.currentThread()) 107 | throw new IllegalArgumentException("not in main thread"); 108 | initNotification(); 109 | cancelNotification(); 110 | // use synchronized() to prevent new items in queue2 111 | // new items will not be added to queue1 because mainLooper.post and attach() run in main thread 112 | synchronized (this) { 113 | this.listener = listener; 114 | } 115 | for(QueueItem item : queue1) { 116 | switch(item.type) { 117 | case Connect: listener.onSerialConnect (); break; 118 | case ConnectError: listener.onSerialConnectError (item.e); break; 119 | case Read: listener.onSerialRead (item.datas); break; 120 | case IoError: listener.onSerialIoError (item.e); break; 121 | } 122 | } 123 | for(QueueItem item : queue2) { 124 | switch(item.type) { 125 | case Connect: listener.onSerialConnect (); break; 126 | case ConnectError: listener.onSerialConnectError (item.e); break; 127 | case Read: listener.onSerialRead (item.datas); break; 128 | case IoError: listener.onSerialIoError (item.e); break; 129 | } 130 | } 131 | queue1.clear(); 132 | queue2.clear(); 133 | } 134 | 135 | public void detach() { 136 | if(connected) 137 | createNotification(); 138 | // items already in event queue (posted before detach() to mainLooper) will end up in queue1 139 | // items occurring later, will be moved directly to queue2 140 | // detach() and mainLooper.post run in the main thread, so all items are caught 141 | listener = null; 142 | } 143 | 144 | private void initNotification() { 145 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 146 | NotificationChannel nc = new NotificationChannel(Constants.NOTIFICATION_CHANNEL, "Background service", NotificationManager.IMPORTANCE_LOW); 147 | nc.setShowBadge(false); 148 | NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 149 | nm.createNotificationChannel(nc); 150 | } 151 | } 152 | 153 | @RequiresApi(Build.VERSION_CODES.O) 154 | public boolean areNotificationsEnabled() { 155 | NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 156 | NotificationChannel nc = nm.getNotificationChannel(Constants.NOTIFICATION_CHANNEL); 157 | return nm.areNotificationsEnabled() && nc != null && nc.getImportance() > NotificationManager.IMPORTANCE_NONE; 158 | } 159 | 160 | private void createNotification() { 161 | Intent disconnectIntent = new Intent() 162 | .setPackage(getPackageName()) 163 | .setAction(Constants.INTENT_ACTION_DISCONNECT); 164 | Intent restartIntent = new Intent() 165 | .setClassName(this, Constants.INTENT_CLASS_MAIN_ACTIVITY) 166 | .setAction(Intent.ACTION_MAIN) 167 | .addCategory(Intent.CATEGORY_LAUNCHER); 168 | int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0; 169 | PendingIntent disconnectPendingIntent = PendingIntent.getBroadcast(this, 1, disconnectIntent, flags); 170 | PendingIntent restartPendingIntent = PendingIntent.getActivity(this, 1, restartIntent, flags); 171 | NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL) 172 | .setSmallIcon(R.drawable.ic_notification) 173 | .setColor(getResources().getColor(R.color.colorPrimary)) 174 | .setContentTitle(getResources().getString(R.string.app_name)) 175 | .setContentText(socket != null ? "Connected to "+socket.getName() : "Background Service") 176 | .setContentIntent(restartPendingIntent) 177 | .setOngoing(true) 178 | .addAction(new NotificationCompat.Action(R.drawable.ic_clear_white_24dp, "Disconnect", disconnectPendingIntent)); 179 | // @drawable/ic_notification created with Android Studio -> New -> Image Asset using @color/colorPrimaryDark as background color 180 | // Android < API 21 does not support vectorDrawables in notifications, so both drawables used here, are created as .png instead of .xml 181 | Notification notification = builder.build(); 182 | startForeground(Constants.NOTIFY_MANAGER_START_FOREGROUND_SERVICE, notification); 183 | } 184 | 185 | private void cancelNotification() { 186 | stopForeground(true); 187 | } 188 | 189 | /** 190 | * SerialListener 191 | */ 192 | public void onSerialConnect() { 193 | if(connected) { 194 | synchronized (this) { 195 | if (listener != null) { 196 | mainLooper.post(() -> { 197 | if (listener != null) { 198 | listener.onSerialConnect(); 199 | } else { 200 | queue1.add(new QueueItem(QueueType.Connect)); 201 | } 202 | }); 203 | } else { 204 | queue2.add(new QueueItem(QueueType.Connect)); 205 | } 206 | } 207 | } 208 | } 209 | 210 | public void onSerialConnectError(Exception e) { 211 | if(connected) { 212 | synchronized (this) { 213 | if (listener != null) { 214 | mainLooper.post(() -> { 215 | if (listener != null) { 216 | listener.onSerialConnectError(e); 217 | } else { 218 | queue1.add(new QueueItem(QueueType.ConnectError, e)); 219 | disconnect(); 220 | } 221 | }); 222 | } else { 223 | queue2.add(new QueueItem(QueueType.ConnectError, e)); 224 | disconnect(); 225 | } 226 | } 227 | } 228 | } 229 | 230 | public void onSerialRead(ArrayDeque datas) { throw new UnsupportedOperationException(); } 231 | 232 | /** 233 | * reduce number of UI updates by merging data chunks. 234 | * Data can arrive at hundred chunks per second, but the UI can only 235 | * perform a dozen updates if receiveText already contains much text. 236 | * 237 | * On new data inform UI thread once (1). 238 | * While not consumed (2), add more data (3). 239 | */ 240 | public void onSerialRead(byte[] data) { 241 | if(connected) { 242 | synchronized (this) { 243 | if (listener != null) { 244 | boolean first; 245 | synchronized (lastRead) { 246 | first = lastRead.datas.isEmpty(); // (1) 247 | lastRead.add(data); // (3) 248 | } 249 | if(first) { 250 | mainLooper.post(() -> { 251 | ArrayDeque datas; 252 | synchronized (lastRead) { 253 | datas = lastRead.datas; 254 | lastRead.init(); // (2) 255 | } 256 | if (listener != null) { 257 | listener.onSerialRead(datas); 258 | } else { 259 | queue1.add(new QueueItem(QueueType.Read, datas)); 260 | } 261 | }); 262 | } 263 | } else { 264 | if(queue2.isEmpty() || queue2.getLast().type != QueueType.Read) 265 | queue2.add(new QueueItem(QueueType.Read)); 266 | queue2.getLast().add(data); 267 | } 268 | } 269 | } 270 | } 271 | 272 | public void onSerialIoError(Exception e) { 273 | if(connected) { 274 | synchronized (this) { 275 | if (listener != null) { 276 | mainLooper.post(() -> { 277 | if (listener != null) { 278 | listener.onSerialIoError(e); 279 | } else { 280 | queue1.add(new QueueItem(QueueType.IoError, e)); 281 | disconnect(); 282 | } 283 | }); 284 | } else { 285 | queue2.add(new QueueItem(QueueType.IoError, e)); 286 | disconnect(); 287 | } 288 | } 289 | } 290 | } 291 | 292 | } 293 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/SerialSocket.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.app.Activity; 4 | import android.bluetooth.BluetoothDevice; 5 | import android.bluetooth.BluetoothSocket; 6 | import android.content.BroadcastReceiver; 7 | import android.content.Context; 8 | import android.content.Intent; 9 | import android.content.IntentFilter; 10 | 11 | import androidx.core.content.ContextCompat; 12 | 13 | import java.io.IOException; 14 | import java.security.InvalidParameterException; 15 | import java.util.Arrays; 16 | import java.util.UUID; 17 | import java.util.concurrent.Executors; 18 | 19 | class SerialSocket implements Runnable { 20 | 21 | private static final UUID BLUETOOTH_SPP = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 22 | 23 | private final BroadcastReceiver disconnectBroadcastReceiver; 24 | 25 | private final Context context; 26 | private SerialListener listener; 27 | private final BluetoothDevice device; 28 | private BluetoothSocket socket; 29 | private boolean connected; 30 | 31 | SerialSocket(Context context, BluetoothDevice device) { 32 | if(context instanceof Activity) 33 | throw new InvalidParameterException("expected non UI context"); 34 | this.context = context; 35 | this.device = device; 36 | disconnectBroadcastReceiver = new BroadcastReceiver() { 37 | @Override 38 | public void onReceive(Context context, Intent intent) { 39 | if(listener != null) 40 | listener.onSerialIoError(new IOException("background disconnect")); 41 | disconnect(); // disconnect now, else would be queued until UI re-attached 42 | } 43 | }; 44 | } 45 | 46 | String getName() { 47 | return device.getName() != null ? device.getName() : device.getAddress(); 48 | } 49 | 50 | /** 51 | * connect-success and most connect-errors are returned asynchronously to listener 52 | */ 53 | void connect(SerialListener listener) throws IOException { 54 | this.listener = listener; 55 | ContextCompat.registerReceiver(context, disconnectBroadcastReceiver, new IntentFilter(Constants.INTENT_ACTION_DISCONNECT), ContextCompat.RECEIVER_NOT_EXPORTED); 56 | Executors.newSingleThreadExecutor().submit(this); 57 | } 58 | 59 | void disconnect() { 60 | listener = null; // ignore remaining data and errors 61 | // connected = false; // run loop will reset connected 62 | if(socket != null) { 63 | try { 64 | socket.close(); 65 | } catch (Exception ignored) { 66 | } 67 | socket = null; 68 | } 69 | try { 70 | context.unregisterReceiver(disconnectBroadcastReceiver); 71 | } catch (Exception ignored) { 72 | } 73 | } 74 | 75 | void write(byte[] data) throws IOException { 76 | if (!connected) 77 | throw new IOException("not connected"); 78 | socket.getOutputStream().write(data); 79 | } 80 | 81 | @Override 82 | public void run() { // connect & read 83 | try { 84 | socket = device.createRfcommSocketToServiceRecord(BLUETOOTH_SPP); 85 | socket.connect(); 86 | if(listener != null) 87 | listener.onSerialConnect(); 88 | } catch (Exception e) { 89 | if(listener != null) 90 | listener.onSerialConnectError(e); 91 | try { 92 | socket.close(); 93 | } catch (Exception ignored) { 94 | } 95 | socket = null; 96 | return; 97 | } 98 | connected = true; 99 | try { 100 | byte[] buffer = new byte[1024]; 101 | int len; 102 | //noinspection InfiniteLoopStatement 103 | while (true) { 104 | len = socket.getInputStream().read(buffer); 105 | byte[] data = Arrays.copyOf(buffer, len); 106 | if(listener != null) 107 | listener.onSerialRead(data); 108 | } 109 | } catch (Exception e) { 110 | connected = false; 111 | if (listener != null) 112 | listener.onSerialIoError(e); 113 | try { 114 | socket.close(); 115 | } catch (Exception ignored) { 116 | } 117 | socket = null; 118 | } 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/TerminalFragment.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.Manifest; 4 | import android.app.Activity; 5 | import android.app.AlertDialog; 6 | import android.bluetooth.BluetoothAdapter; 7 | import android.bluetooth.BluetoothDevice; 8 | import android.content.ComponentName; 9 | import android.content.Context; 10 | import android.content.Intent; 11 | import android.content.ServiceConnection; 12 | import android.os.Build; 13 | import android.os.Bundle; 14 | import android.os.IBinder; 15 | import android.text.Editable; 16 | import android.text.Spannable; 17 | import android.text.SpannableStringBuilder; 18 | import android.text.method.ScrollingMovementMethod; 19 | import android.text.style.ForegroundColorSpan; 20 | import android.view.LayoutInflater; 21 | import android.view.Menu; 22 | import android.view.MenuInflater; 23 | import android.view.MenuItem; 24 | import android.view.View; 25 | import android.view.ViewGroup; 26 | import android.widget.TextView; 27 | import android.widget.Toast; 28 | 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.Nullable; 31 | import androidx.fragment.app.Fragment; 32 | 33 | import java.util.ArrayDeque; 34 | import java.util.Arrays; 35 | 36 | public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener { 37 | 38 | private enum Connected { False, Pending, True } 39 | 40 | private String deviceAddress; 41 | private SerialService service; 42 | 43 | private TextView receiveText; 44 | private TextView sendText; 45 | private TextUtil.HexWatcher hexWatcher; 46 | 47 | private Connected connected = Connected.False; 48 | private boolean initialStart = true; 49 | private boolean hexEnabled = false; 50 | private boolean pendingNewline = false; 51 | private String newline = TextUtil.newline_crlf; 52 | 53 | /* 54 | * Lifecycle 55 | */ 56 | @Override 57 | public void onCreate(@Nullable Bundle savedInstanceState) { 58 | super.onCreate(savedInstanceState); 59 | setHasOptionsMenu(true); 60 | setRetainInstance(true); 61 | deviceAddress = getArguments().getString("device"); 62 | } 63 | 64 | @Override 65 | public void onDestroy() { 66 | if (connected != Connected.False) 67 | disconnect(); 68 | getActivity().stopService(new Intent(getActivity(), SerialService.class)); 69 | super.onDestroy(); 70 | } 71 | 72 | @Override 73 | public void onStart() { 74 | super.onStart(); 75 | if(service != null) 76 | service.attach(this); 77 | else 78 | getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change 79 | } 80 | 81 | @Override 82 | public void onStop() { 83 | if(service != null && !getActivity().isChangingConfigurations()) 84 | service.detach(); 85 | super.onStop(); 86 | } 87 | 88 | @SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions 89 | @Override 90 | public void onAttach(@NonNull Activity activity) { 91 | super.onAttach(activity); 92 | getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE); 93 | } 94 | 95 | @Override 96 | public void onDetach() { 97 | try { getActivity().unbindService(this); } catch(Exception ignored) {} 98 | super.onDetach(); 99 | } 100 | 101 | @Override 102 | public void onResume() { 103 | super.onResume(); 104 | if(initialStart && service != null) { 105 | initialStart = false; 106 | getActivity().runOnUiThread(this::connect); 107 | } 108 | } 109 | 110 | @Override 111 | public void onServiceConnected(ComponentName name, IBinder binder) { 112 | service = ((SerialService.SerialBinder) binder).getService(); 113 | service.attach(this); 114 | if(initialStart && isResumed()) { 115 | initialStart = false; 116 | getActivity().runOnUiThread(this::connect); 117 | } 118 | } 119 | 120 | @Override 121 | public void onServiceDisconnected(ComponentName name) { 122 | service = null; 123 | } 124 | 125 | /* 126 | * UI 127 | */ 128 | @Override 129 | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 130 | View view = inflater.inflate(R.layout.fragment_terminal, container, false); 131 | receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans 132 | receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans 133 | receiveText.setMovementMethod(ScrollingMovementMethod.getInstance()); 134 | 135 | sendText = view.findViewById(R.id.send_text); 136 | hexWatcher = new TextUtil.HexWatcher(sendText); 137 | hexWatcher.enable(hexEnabled); 138 | sendText.addTextChangedListener(hexWatcher); 139 | sendText.setHint(hexEnabled ? "HEX mode" : ""); 140 | 141 | View sendBtn = view.findViewById(R.id.send_btn); 142 | sendBtn.setOnClickListener(v -> send(sendText.getText().toString())); 143 | return view; 144 | } 145 | 146 | @Override 147 | public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) { 148 | inflater.inflate(R.menu.menu_terminal, menu); 149 | } 150 | 151 | public void onPrepareOptionsMenu(@NonNull Menu menu) { 152 | menu.findItem(R.id.hex).setChecked(hexEnabled); 153 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 154 | menu.findItem(R.id.backgroundNotification).setChecked(service != null && service.areNotificationsEnabled()); 155 | } else { 156 | menu.findItem(R.id.backgroundNotification).setChecked(true); 157 | menu.findItem(R.id.backgroundNotification).setEnabled(false); 158 | } 159 | } 160 | 161 | @Override 162 | public boolean onOptionsItemSelected(MenuItem item) { 163 | int id = item.getItemId(); 164 | if (id == R.id.clear) { 165 | receiveText.setText(""); 166 | return true; 167 | } else if (id == R.id.newline) { 168 | String[] newlineNames = getResources().getStringArray(R.array.newline_names); 169 | String[] newlineValues = getResources().getStringArray(R.array.newline_values); 170 | int pos = java.util.Arrays.asList(newlineValues).indexOf(newline); 171 | AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 172 | builder.setTitle("Newline"); 173 | builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> { 174 | newline = newlineValues[item1]; 175 | dialog.dismiss(); 176 | }); 177 | builder.create().show(); 178 | return true; 179 | } else if (id == R.id.hex) { 180 | hexEnabled = !hexEnabled; 181 | sendText.setText(""); 182 | hexWatcher.enable(hexEnabled); 183 | sendText.setHint(hexEnabled ? "HEX mode" : ""); 184 | item.setChecked(hexEnabled); 185 | return true; 186 | } else if (id == R.id.backgroundNotification) { 187 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 188 | if (!service.areNotificationsEnabled() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 189 | requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, 0); 190 | } else { 191 | showNotificationSettings(); 192 | } 193 | } 194 | return true; 195 | } else { 196 | return super.onOptionsItemSelected(item); 197 | } 198 | } 199 | 200 | /* 201 | * Serial + UI 202 | */ 203 | private void connect() { 204 | try { 205 | BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 206 | BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); 207 | status("connecting..."); 208 | connected = Connected.Pending; 209 | SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device); 210 | service.connect(socket); 211 | } catch (Exception e) { 212 | onSerialConnectError(e); 213 | } 214 | } 215 | 216 | private void disconnect() { 217 | connected = Connected.False; 218 | service.disconnect(); 219 | } 220 | 221 | private void send(String str) { 222 | if(connected != Connected.True) { 223 | Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show(); 224 | return; 225 | } 226 | try { 227 | String msg; 228 | byte[] data; 229 | if(hexEnabled) { 230 | StringBuilder sb = new StringBuilder(); 231 | TextUtil.toHexString(sb, TextUtil.fromHexString(str)); 232 | TextUtil.toHexString(sb, newline.getBytes()); 233 | msg = sb.toString(); 234 | data = TextUtil.fromHexString(msg); 235 | } else { 236 | msg = str; 237 | data = (str + newline).getBytes(); 238 | } 239 | SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n'); 240 | spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 241 | receiveText.append(spn); 242 | service.write(data); 243 | } catch (Exception e) { 244 | onSerialIoError(e); 245 | } 246 | } 247 | 248 | private void receive(ArrayDeque datas) { 249 | SpannableStringBuilder spn = new SpannableStringBuilder(); 250 | for (byte[] data : datas) { 251 | if (hexEnabled) { 252 | spn.append(TextUtil.toHexString(data)).append('\n'); 253 | } else { 254 | String msg = new String(data); 255 | if (newline.equals(TextUtil.newline_crlf) && msg.length() > 0) { 256 | // don't show CR as ^M if directly before LF 257 | msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf); 258 | // special handling if CR and LF come in separate fragments 259 | if (pendingNewline && msg.charAt(0) == '\n') { 260 | if(spn.length() >= 2) { 261 | spn.delete(spn.length() - 2, spn.length()); 262 | } else { 263 | Editable edt = receiveText.getEditableText(); 264 | if (edt != null && edt.length() >= 2) 265 | edt.delete(edt.length() - 2, edt.length()); 266 | } 267 | } 268 | pendingNewline = msg.charAt(msg.length() - 1) == '\r'; 269 | } 270 | spn.append(TextUtil.toCaretString(msg, newline.length() != 0)); 271 | } 272 | } 273 | receiveText.append(spn); 274 | } 275 | 276 | private void status(String str) { 277 | SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n'); 278 | spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 279 | receiveText.append(spn); 280 | } 281 | 282 | /* 283 | * starting with Android 14, notifications are not shown in notification bar by default when App is in background 284 | */ 285 | 286 | private void showNotificationSettings() { 287 | Intent intent = new Intent(); 288 | intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS"); 289 | intent.putExtra("android.provider.extra.APP_PACKAGE", getActivity().getPackageName()); 290 | startActivity(intent); 291 | } 292 | 293 | @Override 294 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 295 | if(Arrays.equals(permissions, new String[]{Manifest.permission.POST_NOTIFICATIONS}) && 296 | Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !service.areNotificationsEnabled()) 297 | showNotificationSettings(); 298 | } 299 | 300 | /* 301 | * SerialListener 302 | */ 303 | @Override 304 | public void onSerialConnect() { 305 | status("connected"); 306 | connected = Connected.True; 307 | } 308 | 309 | @Override 310 | public void onSerialConnectError(Exception e) { 311 | status("connection failed: " + e.getMessage()); 312 | disconnect(); 313 | } 314 | 315 | @Override 316 | public void onSerialRead(byte[] data) { 317 | ArrayDeque datas = new ArrayDeque<>(); 318 | datas.add(data); 319 | receive(datas); 320 | } 321 | 322 | public void onSerialRead(ArrayDeque datas) { 323 | receive(datas); 324 | } 325 | 326 | @Override 327 | public void onSerialIoError(Exception e) { 328 | status("connection lost: " + e.getMessage()); 329 | disconnect(); 330 | } 331 | 332 | } 333 | -------------------------------------------------------------------------------- /app/src/main/java/de/kai_morich/simple_bluetooth_terminal/TextUtil.java: -------------------------------------------------------------------------------- 1 | package de.kai_morich.simple_bluetooth_terminal; 2 | 3 | import android.text.Editable; 4 | import android.text.InputType; 5 | import android.text.Spannable; 6 | import android.text.SpannableStringBuilder; 7 | import android.text.TextWatcher; 8 | import android.text.style.BackgroundColorSpan; 9 | import android.widget.TextView; 10 | 11 | import androidx.annotation.ColorInt; 12 | 13 | import java.io.ByteArrayOutputStream; 14 | 15 | final class TextUtil { 16 | 17 | @ColorInt static int caretBackground = 0xff666666; 18 | 19 | final static String newline_crlf = "\r\n"; 20 | final static String newline_lf = "\n"; 21 | 22 | static byte[] fromHexString(final CharSequence s) { 23 | ByteArrayOutputStream buf = new ByteArrayOutputStream(); 24 | byte b = 0; 25 | int nibble = 0; 26 | for(int pos = 0; pos='0' && c<='9') { nibble++; b *= 16; b += c-'0'; } 34 | if(c>='A' && c<='F') { nibble++; b *= 16; b += c-'A'+10; } 35 | if(c>='a' && c<='f') { nibble++; b *= 16; b += c-'a'+10; } 36 | } 37 | if(nibble>0) 38 | buf.write(b); 39 | return buf.toByteArray(); 40 | } 41 | 42 | static String toHexString(final byte[] buf) { 43 | return toHexString(buf, 0, buf.length); 44 | } 45 | 46 | static String toHexString(final byte[] buf, int begin, int end) { 47 | StringBuilder sb = new StringBuilder(3*(end-begin)); 48 | toHexString(sb, buf, begin, end); 49 | return sb.toString(); 50 | } 51 | 52 | static void toHexString(StringBuilder sb, final byte[] buf) { 53 | toHexString(sb, buf, 0, buf.length); 54 | } 55 | 56 | static void toHexString(StringBuilder sb, final byte[] buf, int begin, int end) { 57 | for(int pos=begin; pos0) 59 | sb.append(' '); 60 | int c; 61 | c = (buf[pos]&0xff) / 16; 62 | if(c >= 10) c += 'A'-10; 63 | else c += '0'; 64 | sb.append((char)c); 65 | c = (buf[pos]&0xff) % 16; 66 | if(c >= 10) c += 'A'-10; 67 | else c += '0'; 68 | sb.append((char)c); 69 | } 70 | } 71 | 72 | /** 73 | * use https://en.wikipedia.org/wiki/Caret_notation to avoid invisible control characters 74 | */ 75 | static CharSequence toCaretString(CharSequence s, boolean keepNewline) { 76 | return toCaretString(s, keepNewline, s.length()); 77 | } 78 | 79 | static CharSequence toCaretString(CharSequence s, boolean keepNewline, int length) { 80 | boolean found = false; 81 | for (int pos = 0; pos < length; pos++) { 82 | if (s.charAt(pos) < 32 && (!keepNewline ||s.charAt(pos)!='\n')) { 83 | found = true; 84 | break; 85 | } 86 | } 87 | if(!found) 88 | return s; 89 | SpannableStringBuilder sb = new SpannableStringBuilder(); 90 | for(int pos=0; pos= '0' && c <= '9') sb.append(c); 140 | if(c >= 'A' && c <= 'F') sb.append(c); 141 | if(c >= 'a' && c <= 'f') sb.append((char)(c+'A'-'a')); 142 | } 143 | for(i=2; i 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_send_white_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 13 | 14 | 19 | 20 | 21 | 22 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/res/layout/device_list_header.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/layout/device_list_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 16 | 17 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_terminal.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 18 | 19 | 23 | 24 | 28 | 29 | 36 | 37 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_devices.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_terminal.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 9 | 13 | 18 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kai-morich/SimpleBluetoothTerminal/685a2bb2f06cd4e4c4efc90d5e859ba5f9b2ec3c/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kai-morich/SimpleBluetoothTerminal/685a2bb2f06cd4e4c4efc90d5e859ba5f9b2ec3c/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kai-morich/SimpleBluetoothTerminal/685a2bb2f06cd4e4c4efc90d5e859ba5f9b2ec3c/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kai-morich/SimpleBluetoothTerminal/685a2bb2f06cd4e4c4efc90d5e859ba5f9b2ec3c/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kai-morich/SimpleBluetoothTerminal/685a2bb2f06cd4e4c4efc90d5e859ba5f9b2ec3c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values/arrays.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CR+LF 5 | LF 6 | <none> 7 | 8 | 9 | \u000d\u000a 10 | \u000a 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #d84315 4 | #bf360c 5 | #ff6e40 6 | 7 | #00FF00 8 | #82CAFF 9 | #FFDB58 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Simple Bluetooth Terminal 3 | Bluetooth Devices 4 | 5 | Bluetooth permission 6 | Bluetooth permission is required by this App. Please grant in next dialog. 7 | Bluetooth permission was permanently denied. You have to enable permission \"%s\" in App settings. 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:8.2.1' 8 | } 9 | } 10 | 11 | allprojects { 12 | repositories { 13 | google() 14 | mavenCentral() 15 | } 16 | } 17 | 18 | task clean(type: Delete) { 19 | delete rootProject.buildDir 20 | } 21 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | android.defaults.buildfeatures.buildconfig=true 10 | android.enableJetifier=true 11 | android.useAndroidX=true 12 | org.gradle.jvmargs=-Xmx1536m 13 | # When configured, Gradle will run in incubating parallel mode. 14 | # This option should only be used with decoupled projects. More details, visit 15 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 16 | # org.gradle.parallel=true 17 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kai-morich/SimpleBluetoothTerminal/685a2bb2f06cd4e4c4efc90d5e859ba5f9b2ec3c/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Apr 15 19:29:24 CEST 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------