service discovery failed, except on first connect - java

I'm connecting my Android phone to a HC-05 bluetooth module. It kinda works, I can get some I/O done, but I also get some errors. First error I want to deal with is that I get a "Service Discovery Failed" IO Exception every time I connect to my Bluetooth device, except the first time. Only after a reboot of the phone will it cleanly connect. So, I'd expect something left open, but the only thing I can think of is the socket, and I close that.
09-16 13:55:16.463 8085-8085/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] Bluetooth Socket Constructor
09-16 13:55:16.463 8085-8085/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] type=1 fd=-1 auth=false encrypt=false port=-1
09-16 13:55:16.466 8085-8085/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] connect: do SDP
09-16 13:55:16.738 8085-8098/ltd.arctura.laro_can_bus I/BluetoothSocket_MTK: [JSR82] SdpHelper::onRfcommChannelFound: channel=-1
09-16 13:55:16.757 8085-8085/ltd.arctura.laro_can_bus W/System.err: java.io.IOException: Service discovery failed
09-16 13:55:16.757 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:813)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:382)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at ltd.arctura.laro_can_bus.bluetooth$1.onItemClick(bluetooth.java:173)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:298)
09-16 13:55:16.758 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.widget.AbsListView$1.run(AbsListView.java:3571)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.os.Handler.handleCallback(Handler.java:725)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.os.Looper.loop(Looper.java:153)
09-16 13:55:16.759 8085-8085/ltd.arctura.laro_can_bus W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5341)
09-16 13:55:16.760 8085-8085/ltd.arctura.laro_can_bus W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
09-16 13:55:16.760 8085-8085/ltd.arctura.laro_can_bus W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
09-16 13:55:16.760 8085-8085/ltd.arctura.laro_can_bus W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
09-16 13:55:16.761 8085-8085/ltd.arctura.laro_can_bus W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
09-16 13:55:16.765 8085-8085/ltd.arctura.laro_can_bus W/System.err: at dalvik.system.NativeStart.main(Native Method)
Restarting the HC-05 or the bluetooth on the phone both are not enough.
I have verified the UUID is correct by doing:
ParcelUuid[] uuids=btHC05.getUuids();
if (uuids != null) {
msg(uuids[0].toString());
} else {
msg("No UUID!?");
}
This yields the same UUID as I had configured.
I tried to do a .close on the socket, but that's not helping. I have no input or output streams to close.
The device is already paired and proved to work. I generally don't understand how the Connect() can throw a service discovery failed.. I wouldn't expect the connect() to do any discovery..
private BluetoothAdapter myBluetooth = null;
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
String address = null;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
and
try {
if (btSocket == null) {
BluetoothDevice btHC05 = myBluetooth.getRemoteDevice(address);
btSocket = btHC05.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
}
catch (IOException e){
Toast.makeText(getApplicationContext(), "Error: " + e.toString(), Toast.LENGTH_LONG).show();
ConnectSuccess = false;
}
if (!ConnectSuccess)
{
finish();
}
else {
msg("Connected.");
Intent returnIntent = new Intent();
returnIntent.putExtra("address",address);
setResult(MainActivity.RESULT_OK,returnIntent);
finish();
}
}
There is some more, but this is what is relevant.. It's a bit messy because I've been trialling-erroring a lot ;-)
Also, and this might be relevant. All this happens in a separate activity that gives the user a list of BT-devices to choose from, and then goes back to the Main_Activity.

Related

MediaRecorder stop() failed

I know there are a few of these on SO already but none of them really were able to help my issue, but when I am running the code and start recording audio and then press my stop button it always fails because it is in the wrong state. I am not sure how I would go about fixing my states for this.
Here is my MainActivity.java code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
Button buttonStartRecording, buttonStopRecording, buttonPlayLastRecordAudio,
buttonStopPlayingRecording;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder;
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer;
AudioManager audioManager;
boolean isAudioPlayInSameDevice = true;
// AudioRouter audioRouter;
RadioGroup mRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartRecording = (Button) findViewById(R.id.start_recording);
buttonStopRecording = (Button) findViewById(R.id.stop_rec);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.play_last_rec);
buttonStopPlayingRecording = (Button) findViewById(R.id.stop_playing_btn);
// mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = 1;
if (selectedId == 1) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MediaRecorderReady();
}
}
}
});
}
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) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#RequiresApi(api = Build.VERSION_CODES.O)
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
// if (StoragePermission && RecordPermission) {
// Toast.makeText(BluetoothAudioRecorder.this, "Permission Granted",
// Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(BluetoothAudioRecorder.this,"Permission Denied",Toast.LENGTH_LONG).show();
// }
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
And then my logcat of when the error occurs:
2019-11-24 11:26:54.440 29627-29683/com.example.esense_application E/libc: Access denied finding property "vendor.gralloc.disable_ahardware_buffer"
2019-11-24 11:26:54.435 29627-29627/com.example.esense_application W/RenderThread: type=1400 audit(0.0:17779): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=24699 scontext=u:r:untrusted_app:s0:c7,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 2
2019-11-24 11:26:54.868 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:57.769 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: java.io.FileNotFoundException: /storage/emulated/0/AudioRecording.3gp: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at com.example.esense_application.MainActivity$1.onClick(MainActivity.java:67)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClick(View.java:7140)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClickInternal(View.java:7117)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.access$3500(View.java:801)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View$PerformClick.run(View.java:27351)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Looper.loop(Looper.java:214)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.Linux.open(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: ... 15 more
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application E/MediaRecorder: stop called in an invalid state: 4
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application D/AndroidRuntime: Shutting down VM
2019-11-24 11:27:03.529 29627-29627/com.example.esense_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.esense_application, PID: 29627
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.esense_application.MainActivity$2.onClick(MainActivity.java:98)
at android.view.View.performClick(View.java:7140)
at android.view.View.performClickInternal(View.java:7117)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27351)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:03.540 29627-29627/com.example.esense_application I/Process: Sending signal. PID: 29627 SIG: 9
Your MediaRecorder is throwing when you try to stop() it because it has never entered the "recording" state. In fact, it never even entered the "prepared" state, because your call to prepare() did not complete successfully.
SOLUTION
Do not allow a call to start() until the prepare() call has returned (without throwing).
Do not allow a call to stop() until the start() call has returned (without throwing).
Make sure you have chosen a valid location for your output file. Try using getExternalFilesDir( null ) instead of Environment.getExternalStorageDirectory(). The bad file path is the reason your prepare() call is currently failing with an EACCESS.
As you can see, swallowing exceptions without addressing their root cause (i.e., just doing a e.printStackTrace() and carrying on), can rapidly lead to problems -- even in rough code used for learning/experimentation. If you are going to add an exception handler, it is better to provide real error handling -- and always make sure you understand why an exception is being thrown.

Has been running on another Thread, but still thrown android.os.NetworkOnMainThreadException? [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
public class Client extends AppCompatActivity {
public static final String TAG = Client.class.getSimpleName();
public static final int ServerPORT = 3000;
public static final String ServerIP = "10.146.166.86";
EditText message;
TextView mainView;
ClientThread clientThread;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
message = (EditText)findViewById(R.id.message);
mainView = (TextView)findViewById(R.id.mainView);
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mainView.append(message + "\n");
}
});
}
public void onClick(View view) {
if (view.getId() == R.id.connectServer) {
mainView.setText("");
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.sendMessage) {
Log.i(TAG, "Message sent from client");
clientThread.sendMessage(message.getText().toString());
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
#Override
public void run() {
try {
InetAddress serverAdd = InetAddress.getByName(ServerIP);
socket = new Socket(serverAdd, ServerPORT);
while (!Thread.currentThread().isInterrupted()) {
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
updateMessage(getTime() + " | Server : " + message);
break;
}
updateMessage(getTime() + " | Server : " + message);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
void sendMessage(String message) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
I wrote a simple server-client TCP socket connection, and have been trying to connect between the host and the client. Although I already ran the network operations on the other Thread (not the mainThread), when I try to send a string from the client to my server, it throws
android.os.NetworkOnMainThreadException.
It seems even more weird to me because when I try switching the host and client devices, now I am able to send from the client to my server, but not from the server to the client. Then, I conclude that it should be due to one of my devices. One runs Android 8 and one runs Android 6, and it seems the problem belongs to the one running Android 8. Although I succesfully overcame this problem by adding:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
It seems really weird to me because the way it happens. Does it actually depend on the device?
Edit: Full error message. It's weird because it only happens with one of my devices. When I switch the roles between devices, it does its job successfully.
02-10 16:42:17.719 827-827/com.dev.kvuong2711.clienttcp I/Client: Message sent from client
02-10 16:42:17.720 827-827/com.dev.kvuong2711.clienttcp W/System.err: android.os.NetworkOnMainThreadException
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:108)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
02-10 16:42:17.721 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.BufferedWriter.flush(BufferedWriter.java:254)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.io.PrintWriter.newLine(PrintWriter.java:482)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.dev.kvuong2711.clienttcp.Client$ClientThread.sendMessage(Client.java:105)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.dev.kvuong2711.clienttcp.Client.onClick(Client.java:68)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.view.View.performClick(View.java:6256)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.view.View$PerformClick.run(View.java:24779)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Handler.handleCallback(Handler.java:789)
02-10 16:42:17.722 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:98)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.os.Looper.loop(Looper.java:180)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6950)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
02-10 16:42:17.723 827-827/com.dev.kvuong2711.clienttcp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:835)
Your code in sendMessage is not running on another thread just because you put it in another class called "Thread". Only the run() method of a runnable is running on the other thread, when you call execute(). So you either have to call sendMessage in a new Thread() or put it in some kind of threadsafe variable or queue, that you check in your loop in the run() method and then send away.

Error being thrown when load a map from a KML

I am loading a map in my app from kml files (with a different kml file on each day of the week being loaded). It was working until just recently and I'm really confused as to why I am getting this error as I haven't touched this part of my code since I got it working basically and now I am getting a XmlPullParserException: expected: /META read: HEAD (position:END_TAG #1:355 in java.io.InputStreamReader#426ba9d0)
Here is my code:
// set kml layers
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream inputStream = null;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int value = preferences.getInt("DateStarted", 1);
Log.d(TAG, String.valueOf(value));
System.out.println("In Maps start day is " + String.valueOf(value));
try {
// get different maps on different days of the week
switch(value) {
case Calendar.MONDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/monday.kml").openStream();
break;
case Calendar.TUESDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/tuesday.kml").openStream();
break;
case Calendar.WEDNESDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/wednesday.kml").openStream();
break;
case Calendar.THURSDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/thursday.kml").openStream();
break;
case Calendar.FRIDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/thursday.kml").openStream();
break;
case Calendar.SATURDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/saturday.kml").openStream();
break;
case Calendar.SUNDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/sunday.kml").openStream();
break;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
try {
layer = new KmlLayer(mMap, inputStream, getApplicationContext());
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
layer.addLayerToMap();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
and the full error message that I'm getting is :
> W/System.err: org.xmlpull.v1.XmlPullParserException: expected: /META read: HEAD (position:END_TAG </HEAD>#1:355 in java.io.InputStreamReader#426ba9d0)
W/System.err: at org.kxml2.io.KXmlParser.readEndTag(KXmlParser.java:970)
W/System.err: at org.kxml2.io.KXmlParser.next(KXmlParser.java:372)
W/System.err: at org.kxml2.io.KXmlParser.next(KXmlParser.java:310)
W/System.err: at com.google.maps.android.kml.KmlParser.parseKml(KmlParser.java:90)
W/System.err: at com.google.maps.android.kml.KmlLayer.<init>(KmlLayer.java:49)
W/System.err: at com.example.veronika.grabble.MapsActivity.onMapReady(MapsActivity.java:169)
W/System.err: at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
W/System.err: at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
W/System.err: at android.os.Binder.transact(Binder.java:347)
W/System.err: at aai.a(:com.google.android.gms.DynamiteModulesB:82)
W/System.err: at maps.ad.t$5.run(Unknown Source)
W/System.err: at android.os.Handler.handleCallback(Handler.java:730)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err: at android.os.Looper.loop(Looper.java:213)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5225)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:525)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x420218b0)
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.veronika.grabble.MapsActivity.onMapReady(MapsActivity.java:176)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:347)
at aai.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.t$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Does anyone have an idea of how I should go about fixing this? Because I don't understand where does the null pointer exception comes from...
PS: the log.d shows that value has a value in one of the cases, and so that should put a different inputStream than null ....

Stream video from android to RTSP server

I need to stream video from an android phone to RTSP server and then receive this video on another android phone. I googled a lot but I didn't find a good solution for it. Everything I found was libstreaming but I couldn't run it in my app.
Here is my sample code:
private SurfaceView mSurfaceView;
private Session mSession;
private static RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
initRtspClient();
}
#Override
public void onDestroy() {
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
toggleStreaming();
}
#Override
protected void onPause(){
super.onPause();
toggleStreaming();
}
private void initRtspClient() {
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.setCallback(this).build();
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
mClient.setServerAddress("176.120.25.62", 1235);
}
private void toggleStreaming() {
if (!mClient.isStreaming()) {
mSession.startPreview();
mClient.startStream();
} else {
mSession.stopPreview();
mClient.stopStream();
}
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
exception.printStackTrace();
break;
case RtspClient.ERROR_WRONG_CREDENTIALS:
exception.printStackTrace();
break;
}
}
#Override
public void onPreviewStarted() {
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
}
#Override
public void onSessionStopped() {
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onBitrateUpdate(long bitrate) {
}
LOGCAT:
09-28 21:05:23.357 16654-16654/shkatovl.btandroid I/Timeline: Timeline: Activity_launch_request time:6595904
09-28 21:05:23.507 16654-16664/shkatovl.btandroid W/art: Suspending all threads took: 5.493ms
09-28 21:05:23.618 16654-16654/shkatovl.btandroid I/MediaStream: Phone supports the MediaCoded API
09-28 21:05:23.678 16654-16937/shkatovl.btandroid D/RtspClient: Connecting to RTSP server...
09-28 21:05:23.778 16654-16654/shkatovl.btandroid D/VideoStream: Surface Changed !
09-28 21:05:23.908 16654-16935/shkatovl.btandroid V/VideoQuality: Supported resolutions: 1920x1080, 1280x720, 1280x960, 800x480, 768x432, 720x480, 640x480, 576x432, 480x320, 384x288, 352x288, 320x240, 240x160, 192x112, 176x144
09-28 21:05:23.908 16654-16935/shkatovl.btandroid V/VideoQuality: Supported frame rates: 15-15fps, 12-24fps
09-28 21:05:23.978 16654-16654/shkatovl.btandroid D/VideoStream: Surface Changed !
09-28 21:05:23.998 16654-16654/shkatovl.btandroid I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#3254450a time:6596541
09-28 21:05:24.118 16654-16654/shkatovl.btandroid W/System.err: java.net.ConnectException: failed to connect to /176.120.25.62 (port 1235): connect failed: ECONNREFUSED (Connection refused)
09-28 21:05:24.118 16654-16937/shkatovl.btandroid I/RtspClient: TEARDOWN rtsp://176.120.25.62:1235/ RTSP/1.0
09-28 21:05:24.118 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:124)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.startupSocket(Socket.java:590)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.tryAllAddresses(Socket.java:128)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.<init>(Socket.java:178)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at java.net.Socket.<init>(Socket.java:150)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at net.majorkernelpanic.streaming.rtsp.RtspClient.tryConnection(RtspClient.java:309)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at net.majorkernelpanic.streaming.rtsp.RtspClient.access$500(RtspClient.java:53)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at net.majorkernelpanic.streaming.rtsp.RtspClient$2.run(RtspClient.java:250)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.Looper.loop(Looper.java:135)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at android.os.HandlerThread.run(HandlerThread.java:61)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.Posix.connect(Native Method)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 21:05:24.128 16654-16654/shkatovl.btandroid W/System.err: ... 13 more
So my question is where is my mistake(I added compile to gradle and permissions to manifest) or if you know ways to solve my problem, say me about it.
Thanks!

Getting NetworkOnMainThreadException while implementing Runnable [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 7 years ago.
I'm getting NetworkOnMainThreadException while using Runnable
Code:
public class FullscreenActivity extends AppCompatActivity {
public Socket socket;
public int SERVERPORT = 5000; /* port 5000 (for testing) */
public String SERVER_IP = "10.0.2.2"; /* local Android address of localhost */
ViewFlipper flipper;
ListView listing;
public void attemptConnect(View view) {
try {
EditText editTextAddress = (EditText) findViewById(R.id.address);
EditText editTextPort = (EditText) findViewById(R.id.port);
String SERVER_IP_loc = editTextAddress.getText().toString();
int SERVERPORT_loc = Integer.parseInt(editTextPort.getText().toString());
System.out.println("Attempt Connect: IP " + SERVER_IP_loc + " Port: " + SERVERPORT_loc);
System.out.println("SET");
ClientThread myClientTask = new ClientThread(SERVER_IP_loc, SERVERPORT_loc);
myClientTask.run();
System.out.println("CONNECTED");
flipper.setDisplayedChild(1);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// Thinks the following is not a thread ??
class ClientThread implements Runnable {
ClientThread(String addr, int port) {
SERVER_IP = addr;
SERVERPORT = port;
}
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
// gets to this line fine
socket = new Socket(serverAddr, SERVERPORT);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
My permissions are set up to allow internet access:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I'm getting the following error:
6188-6188/test W/System.err: android.os.NetworkOnMainThreadException
6188-6188/test W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
6188-6188/test W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
6188-6188/test W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
6188-6188/test W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
6188-6188/test W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
6188-6188/test W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
6188-6188/test W/System.err: at java.net.Socket.startupSocket(Socket.java:592)
6188-6188/test W/System.err: at java.net.Socket.<init>(Socket.java:226)
6188-6188/test W/System.err: at test.FullscreenActivity$ClientThread.run(FullscreenActivity.java:363)
6188-6188/test W/System.err: at test(FullscreenActivity.java:340)
6188-6188/test W/System.err: at java.lang.reflect.Method.invoke(Native Method)
6188-6188/test W/System.err: at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(test:270)
6188-6188/test W/System.err: at android.view.View.performClick(View.java:5198)
6188-6188/test W/System.err: at android.view.View$PerformClick.run(View.java:21147)
6188-6188/test W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
6188-6188/test W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
6188-6188/test W/System.err: at android.os.Looper.loop(Looper.java:148)
6188-6188/test W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
6188-6188/test W/System.err: at java.lang.reflect.Method.invoke(Native Method)
6188-6188/test W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
6188-6188/test W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
As far as I can tell, this should function as expected. It seems to think the Runnable isn't a thread, but I can't figure out why.
You need a Thread to run your Runnable for you. Simply calling run on a Runnable does not run it on a different thread.
new Thread(new ClientThread(SERVER_IP_loc, SERVERPORT_loc)).start();

Categories

Resources