Thread run method and handler with DatagramSocket Android - multithreading

I have implemented this code to get data through udp packages but I can read just the first package (Thread run() method run one time). I'm implementing a thread and a handler.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewState = (TextView)findViewById(R.id.state);
new Thread() {
#Override
public void run() {
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket datagramSocket = null;
try {
datagramSocket = new DatagramSocket(3333);
} catch (SocketException e) {
e.printStackTrace();
}
try {
datagramSocket.receive(packet);
mHandler.obtainMessage(2, 10, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 2) {
byte[] readRpmBuf = (byte[]) msg.obj;
String val="";
for (int i=0;i<100;i++){
val+=String.valueOf(readRpmBuf[i])+"-";
}
textViewState.setText(val);
}
}
};
}

Related

Cannot run a background task in andorid studio using AsyncTask

I am trying to run a task at background using AsyncTask, but it isn't working
I have tried a lot of solutions but none worked. My code should show me html codes of prothomalo.com at the logcat, but is is not doing that, instead it is showing a lot of errors.
public class BG extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("myBG", "onPreExecute: ran");
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("myBG", "onPostExecute: ran");
Log.d("myBG", s);
}
#Override
protected String doInBackground(String... urls) {
Log.d("myBG", "doInBackground: ran");
String result = "";
URL url;
HttpURLConnection conn;
try {
url = new URL(urls[0]);
conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
return "Something went wrong";
}
return result;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
text = findViewById(R.id.text8);
BG myTask = new BG();
myTask.execute("https://www.prothomalo.com");
}
}The logcat should show if my background activity has run or not, but it showing a lot of errors

Synchronously Send and Receive Bluetooth Data using Kotlin Coroutines

This has been the method so far to send and receive on bluetooth using Java with threading. But how do we do this using Kotlin's latest Coroutines? Alot of this old Java cold no longer translates to Kotlin 1.4+ either in terms of how to do threading. I read Kotlin is now using Coroutines instead of threads like before.
public class MainActivity extends AppCompatActivity {
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66")
public void pairDevice(View v) {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
Object[] devices = pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0]
ConnectThread connect = new ConnectThread(device,MY_UUID_INSECURE);
connect.start();
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) {
}
mmSocket = tmp;
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e1) {
}
}
//will talk about this in the 3rd video
connected(mmSocket);
}
}
private void connected(BluetoothSocket mmSocket) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
final String incomingMessage = new String(buffer, 0, bytes);
runOnUiThread(new Runnable() {
#Override
public void run() {
view_data.setText(incomingMessage);
}
});
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
}
public void SendMessage(View v) {
byte[] bytes = send_data.getText().toString().getBytes(Charset.defaultCharset());
mConnectedThread.write(bytes);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_data =(EditText) findViewById(R.id.editText);
view_data = (TextView) findViewById(R.id.textView);
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void Start_Server(View view) {
AcceptThread accept = new AcceptThread();
accept.start();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null ;
try{
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("appname", MY_UUID_INSECURE);
}catch (IOException e){
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
}catch (IOException e){
}
//talk about this is in the 3rd
if(socket != null){
connected(socket);
}
}
}

Recording with BluetoothHeadset Mic

Hei there,
I m trying to make an App with Android-Studio that can record sound using a Bluetooth-HS.
I know there are a lot of posts close to this, but i tried all the answers and it wont work for me.
My code gives me back a filled bytebuffer, however testing proves, its always the Phones Mic not the Headset-Mic.
If anyone could take a look at my code and point out why it wont use the BT-HS, that would be a huge help for me.
public class Inhalation extends AppCompatActivity {
AudioManager audioManager;
AudioRecord audioRecord=null;
Button mrecord;
Button mpause;
boolean isRecording=false;
private Thread recordingThread = null;
private int bufferSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inhalation);
mrecord= findViewById(R.id.Button_Record_ID);
mpause=findViewById(R.id.Button_Pause_ID);
audioManager =(AudioManager) this.getSystemService(this.AUDIO_SERVICE);
}
//is supposed to start recording using the BT MIC. Can only be called if BTSCO is connected
private void startRecording() {
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audioRecord.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
//picks up the recorded audiobuffer and writes it into a file
private void writeAudioDataToFile() {
String filename="record";
byte saudioBuffer[] = new byte[bufferSize];
FileOutputStream os = null;
// TODO (4) Audiorecord Filecreation
try {
os = openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("headset_rec","false filepath");
}
while (isRecording) {
audioRecord.read(saudioBuffer, 0, bufferSize);
try {
os.write(saudioBuffer, 0, bufferSize);
// os.write(saudioBuffer);
Log.d("headset_rec","writing"+saudioBuffer[0]);
} catch (IOException e) {
e.printStackTrace();
Log.d("headset_rec","writefail");
}
}
try {
os.close();
} catch (IOException e) {
Log.d("headset_rec","close");
e.printStackTrace();
}
}
//stops the recording
private void stopRecording() {
// stops the recording activity
if (null != audioRecord) {
isRecording = false;
audioRecord.stop();
audioRecord.release();
audioRecord = null;
recordingThread = null;
}
}
public void Record_On_Click(View view){
mpause.setEnabled(true);
mrecord.setEnabled(false);
requestRecordAudioPermission();
startRecording();
}
//Button to pause
public void Record_Pause_Click(View view){
stopRecording();
// readFromFile();
mrecord.setEnabled(true);
mpause.setEnabled(false);
}
//if BluetoothSCO is connected enables recording
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
Log.d("SCOO","connected");
mrecord.setEnabled(true);
}
if(AudioManager.SCO_AUDIO_STATE_DISCONNECTED==state){
Log.d("SCOO","disconnected");
mrecord.setEnabled(false);
}
}
};
//connects to the bluetoothHeadset doing the following:
#Override
protected void onResume() {
// TODO (5) Bluetooth Mik
// Start Bluetooth SCO.
if(isRecording){
mpause.setEnabled(true);
mrecord.setEnabled(false);
}
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
super.onResume();
}
//Disconnects from the Bluetoothheadset doing the following
#Override
protected void onDestroy() {
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
unregisterReceiver(mBluetoothScoReceiver);
super.onDestroy();
}
private void requestRecordAudioPermission() {//gets the permission to record audio
//check API version, do nothing if API version < 23!
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
Log.d("Activity_Request", "Wastn granted!");
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
Log.d("Activity_Request", "request!");
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
Log.d("Activity_Request", "take!");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
}
}
}
}

retrofit2.0.0+okhttp3 download logging output OOM

addInterceptor ->HttpLoggingInterceptor bug-->OOM
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
File httpCacheDirectory = new File(MyApplication.mContext.getCacheDir(), "responses");
//设置缓存 10M
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
OkHttpClient client = null;
final TrustManager[] trustManager = new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
};
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client = new OkHttpClient.Builder().addInterceptor(interceptor).sslSocketFactory(sslSocketFactory).addInterceptor(new BaseInterceptor()).hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).cache(cache).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
_instance = new Retrofit.Builder().baseUrl(ConstantUtils.HOST)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();
}
return _instance.create(ICommonService.class);
RetrofitUtils.generateCommonService().down().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
LogUtils.e("errorrrrrrrrrr");
}
#Override
public void onNext(ResponseBody responseBody) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
byte[] by = responseBody.bytes();
File file = new File(BaseApplication.getContext().getFilesDir(), "download.apk");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(by);
LogUtils.e("length=======>",file.length()+"");
mainView.updateApk(file);
}catch (IOException e){
e.printStackTrace();
}finally {
if (bos != null)
{
try
{
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (fos != null)
{
try
{
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
LogUtils.e("success=========");
}
});
When you use HttpLoggingInterceptor.Level.BODY , then you try to download large file , will save all body in memory for log.
That's easy let to OOM .
Try to remove log body or just logging NONE , basic or header and try again.
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
Try this .
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
//设置缓存路径

Yet another "Can't create handler inside thread that has not called Looper.prepare()" topic

I have this code which is an Activity that when started will check for internet connection, if there is a connection, then life goes on. Else a dialog appears to turn on the connection. However I made a thread that each 10 seconds will check for connection and in case the connection was lost it will display the dialog again.
package greensmartcampus.eu.smartcampususerfeedbackapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.net.InetAddress;
public class HomeScreen extends AbstractPortraitActivity {
private static final int WIFI_REQUEST_CODE = 1;
private boolean networkSettingsDialogOpened = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
this.runOnUiThread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
(...)
private boolean isInternetAvailable() {
try {
final InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
private void createNetErrorDialog() {
networkSettingsDialogOpened = true;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You need a network connection to use this application. Please turn on mobile network or Wi-Fi in Settings.")
.setTitle("Unable to connect")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivityForResult(i, WIFI_REQUEST_CODE);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
}
);
final AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == WIFI_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
networkSettingsDialogOpened = false;
Toast.makeText(HomeScreen.this, "Returned Ok",
Toast.LENGTH_LONG).show();
}
if (resultCode == RESULT_CANCELED) {
networkSettingsDialogOpened = false;
Toast.makeText(HomeScreen.this, "Returned Canceled",
Toast.LENGTH_LONG).show();
}
}
}
}
However I am getting the following error:
02-03 18:13:14.525 2683-2699/greensmartcampus.eu.smartcampususerfeedbackapp E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-193
Process: greensmartcampus.eu.smartcampususerfeedbackapp, PID: 2683
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.app.Dialog.<init>(Dialog.java:108)
at android.app.AlertDialog.<init>(AlertDialog.java:125)
at android.app.AlertDialog$Builder.create(AlertDialog.java:967)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen.createNetErrorDialog(HomeScreen.java:97)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen.access$200(HomeScreen.java:15)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen$1.run(HomeScreen.java:29)
Note: Line 97 is the one containing:
final AlertDialog alert = builder.create();
I googled alot, I am already using the cliche answer of runOnUiThread, but it doesn't fix it.
What am I missing?
The way you are checking the internet I guess you are causing your UI thread to sleep. You should do it like this.
Create one Handler and Thread running flag:
Handler mHandler = new Handler();
boolean isRunning = true;
Then, use this thread from your onCreate() method :
new Thread(new Runnable() {
#Override
public void run() {
while (isRunning) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
if(!HomeScreen.this.isInternetAvailable()){
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
}
}
});
} catch (Exception e) {
}
}
}
}).start();
Change this method slightly
private boolean isInternetAvailable() {
try {
final InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
isRunning = true;
return true;
}
} catch (Exception e) {
return false;
}
}
You can't call Thread.sleep() from code that is running on the UI thread. This is your code:
this.runOnUiThread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
You jest need to run the bit of code that shows the Dialog on the UI thread. Try this instead:
new Thread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
// Show the Dialog on the UI thread
HomeScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
HomeScreen.this.createNetErrorDialog();
}
});
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

Resources