All the other breakpoints inside my class work just fine.
However, none of the breakpoints inside the run method. What can the issue be?
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(final Object...args) {
new Handler(getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatService.this, "connected", Toast.LENGTH_SHORT).show();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(user);
try {
obj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("set-user-data", obj, user.getRole());
JSONArray membersJSONArray = new JSONArray();
membersJSONArray.put(user.getUsername());
JSONObject roomInfo = new JSONObject();
try {
roomInfo.put("members", membersJSONArray);
roomInfo.put("platformInfo", user.getPlatformInfo());
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("set-room", roomInfo);
}
});
}
};
Related
I have a splash screen in which i am checking user is logged in or not if logged in go to dashboard otherwise go to login activity. I am using sharedpref. Issue is (which I am unable to resolve) after splash screen login screen appears for a brief moment than dashboard. Splash > Login > Dash what i Want is Splash > Dash (if user logged in). Login is the main activity of my project. Here is the code:
public class SplashScreen extends AppCompatActivity {
private SessionManager sessionManager;
private BroadcastReceiver broadcastReceiver;
private SharedPreferences prefs;
private boolean isLogin;
private int accessID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(this);
broadcastReceiver = new CheckNetStatus();
broadcastIntent();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onResume(){
super.onResume();
new CheckNetStatus().onReceive(SplashScreen.this,new
Intent(ConnectivityManager.CONNECTIVITY_ACTION));
try {
prefs = getSharedPreferences(SessionManager.PREF_NAME, 0); // Declare
SharedPreferences
accessID = prefs.getInt(SessionManager.KEY_ACCESSID, 0); // get Access Id from
SharedPreferences
isLogin = Utils.getLoginStatus(SplashScreen.this); // Check Login is true or false
} catch (Exception e) {
e.printStackTrace();
}
Thread splashTread = new Thread() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void run() { // run thread
try {
synchronized (this) {
Thread.sleep(3000); // Screen stay for 3 sec.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isLogin)
{
// if (accessID == 0) { // access Id is ZERO open AddMoneyActivity.class
// try {
// } catch (Exception e) {
// e.printStackTrace();
// }
// } else if (accessID == 1) {// access Id is ONE open
ProfileStepOneActivity.class
try {
Intent intent = new Intent(SplashScreen.this, Dashboard.class);
startActivity(intent);
finishAffinity(); // Finish stack
} catch (Exception e) {
e.printStackTrace();
}
} else {// Login is False goto Login Activity
try {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
splashTread.start();
}
public void broadcastIntent() {
registerReceiver(broadcastReceiver, new
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
//unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop(){
super.onStop();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
// unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
}
My mistake....i was redirecting to main activity ie login activity in netstats class(where i was checking the net connection) ie why it was showing login screen for a moment issue resolved now
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);
}
}
}
Hi I'm a newbie with RXJava,I am trying to work on my first RxJava example that like below
Observable<String> myObservable = Observable.create(
new Observable.OnSubscribe<String>() {
public void call(Subscriber<? super String> subscriber) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
subscriber.onNext("hello world");
subscriber.onCompleted();
}
}
).subscribeOn(Schedulers.computation());
Observable<String> myObservable1 = Observable.just("thank you");
Observable observable3 = Observable.zip(myObservable, myObservable1, new Func2<String,String,String>() {
#Override
public String call(String o, String o2) {
return o+":"+o2;
}
});
observable3.subscribe(new Action1<String>() {
#Override
public void call(String o) {
System.out.println("before");
System.out.println(o);
}
});
System.out.println("after");
I want to print before then after,how I to do that with rxjava and without sleep
One possible way:
Observable<String> myObservable = Observable.create(
new Observable.OnSubscribe<String>() {
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("hello world");
subscriber.onCompleted();
}
}
).subscribeOn(Schedulers.computation());
Observable<String> myObservable1 = Observable.just("thank you");
Observable observable3 = Observable.zip(myObservable, myObservable1, new Func2<String,String,String>() {
#Override
public String call(String o, String o2) {
return o+":"+o2;
}
});
Observable.just("before").concatWith(observable3).concatWith(Observable.just("after")).toBlocking().subscribe(new Action1<String>() {
#Override
public void call(String s) {
System.out.println(s);
}
});
Result is:
before
hello world:thank you
after
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);
//设置缓存路径
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();