Skip to content

Commit

Permalink
BluetoothChat: Various updates
Browse files Browse the repository at this point in the history
- Migrate to AndroidX
- API level 29
- Prevent NPE on device without Bluetooth

Fixes #103
  • Loading branch information
yaraki committed Sep 19, 2019
1 parent 67005e7 commit 7685824
Show file tree
Hide file tree
Showing 13 changed files with 145 additions and 133 deletions.
73 changes: 20 additions & 53 deletions BluetoothChat/Application/build.gradle
@@ -1,68 +1,35 @@

buildscript {
repositories {
google()
jcenter()
}

dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
}
}
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

apply plugin: 'com.android.application'

repositories {
google()
jcenter()
}

dependencies {


implementation "com.android.support:support-v4:28.0.0"
implementation "com.android.support:support-v13:28.0.0"
implementation "com.android.support:cardview-v7:28.0.0"
implementation "com.android.support:appcompat-v7:28.0.0"






}

// The sample build uses multiple directories to
// keep boilerplate and common code separate from
// the main sample code.
List<String> dirs = [
'main', // main sample code; look here for the interesting stuff.
'common', // components that are reused by multiple samples
'template'] // boilerplate code that is generated by the sample template process

android {
compileSdkVersion 28
compileSdkVersion 29

defaultConfig {
minSdkVersion 14
targetSdkVersion 28
targetSdkVersion 29
}

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}

sourceSets {
main {
dirs.each { dir ->
java.srcDirs "src/${dir}/java"
res.srcDirs "src/${dir}/res"
}
}
androidTest.setRoot('tests')
androidTest.java.srcDirs = ['tests/src']

}

dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
}
17 changes: 9 additions & 8 deletions BluetoothChat/Application/src/main/AndroidManifest.xml
Expand Up @@ -14,39 +14,40 @@
See the License for the specific language governing permissions and
limitations under the License.
-->

<manifest
package="com.example.android.bluetoothchat"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.android.bluetoothchat"
android:versionCode="1"
android:versionName="1.0">

<!-- Min/target SDK versions (<uses-sdk>) managed by build.gradle -->

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">

<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".DeviceListActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/select_device"
android:theme="@android:style/Theme.Holo.Dialog"/>
android:theme="@android:style/Theme.Holo.Dialog" />

</application>

Expand Down
Expand Up @@ -24,9 +24,6 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
Expand All @@ -42,6 +39,11 @@
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.example.android.common.logger.Log;

/**
Expand Down Expand Up @@ -94,17 +96,19 @@ public void onCreate(Bundle savedInstanceState) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
FragmentActivity activity = getActivity();
if (mBluetoothAdapter == null && activity != null) {
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}


@Override
public void onStart() {
super.onStart();
if (mBluetoothAdapter == null) {
return;
}
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Expand Down Expand Up @@ -148,9 +152,9 @@ public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
mConversationView = view.findViewById(R.id.in);
mOutEditText = view.findViewById(R.id.edit_text_out);
mSendButton = view.findViewById(R.id.button_send);
}

/**
Expand All @@ -160,7 +164,11 @@ private void setupChat() {
Log.d(TAG, "setupChat()");

// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
mConversationArrayAdapter = new ArrayAdapter<>(activity, R.layout.message);

mConversationView.setAdapter(mConversationArrayAdapter);

Expand All @@ -173,18 +181,18 @@ public void onClick(View v) {
// Send a message using content of the edit text widget
View view = getView();
if (null != view) {
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
TextView textView = view.findViewById(R.id.edit_text_out);
String message = textView.getText().toString();
sendMessage(message);
}
}
});

// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(getActivity(), mHandler);
mChatService = new BluetoothChatService(activity, mHandler);

// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
mOutStringBuffer = new StringBuffer();
}

/**
Expand Down Expand Up @@ -347,9 +355,12 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) {
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
FragmentActivity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
activity.finish();
}
}
}
}
Expand All @@ -362,16 +373,19 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) {
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
Bundle extras = data.getExtras();
if (extras == null) {
return;
}
String address = extras.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}

Expand Down
Expand Up @@ -329,7 +329,7 @@ public void run() {
"BEGIN mAcceptThread" + this);
setName("AcceptThread" + mSocketType);

BluetoothSocket socket = null;
BluetoothSocket socket;

// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
Expand Down
Expand Up @@ -22,14 +22,14 @@
public interface Constants {

// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
int MESSAGE_STATE_CHANGE = 1;
int MESSAGE_READ = 2;
int MESSAGE_WRITE = 3;
int MESSAGE_DEVICE_NAME = 4;
int MESSAGE_TOAST = 5;

// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
String DEVICE_NAME = "device_name";
String TOAST = "toast";

}
Expand Up @@ -76,7 +76,7 @@ protected void onCreate(Bundle savedInstanceState) {
setResult(Activity.RESULT_CANCELED);

// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
Button scanButton = findViewById(R.id.button_scan);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doDiscovery();
Expand All @@ -87,16 +87,16 @@ public void onClick(View v) {
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
ArrayAdapter<String> pairedDevicesArrayAdapter =
new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
new ArrayAdapter<>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);

// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
ListView pairedListView = findViewById(R.id.paired_devices);
pairedListView.setAdapter(pairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);

// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
ListView newDevicesListView = findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);

Expand Down Expand Up @@ -198,7 +198,7 @@ public void onReceive(Context context, Intent intent) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if (device != null && device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
Expand Down

0 comments on commit 7685824

Please sign in to comment.