my problem is:
I want my application to block buttons or whole activity when there is no internet connection and unblock them when internet connection is back. I'm using BroadcastReceiver to check internet in main activity and it works well:
public class MainActivity extends BroadCast {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
// code
}
To block MainActivity I'm using ProgressDialog with method setCancelable set to false.
BroadCast Activity:
public class BroadCast extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public BroadcastReceiver mConnReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
#SuppressWarnings("deprecation")
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(currentNetworkInfo.isConnected()) {
BlockActivity(true);
}
else {
BlockActivity(false);
}
}
};
public void BlockActivity(Boolean connected)
{
final ProgressDialog pausingDialog = ProgressDialog.show(this, "", "Application waiting for internet connection...");
if (!connected)
{
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
pausingDialog.show();
pausingDialog.setCancelable(false);
}
else
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
pausingDialog.setCancelable(true);
pausingDialog.dismiss();
}
}
}
Toast information works good, but the problem is with ProgressDialog. It shows up when internet connection is gone, but it don't want to disappear when internet connection is back. How to fix it? Thanks.
Keep a global reference to your dialog so you don't keep recreating it. You should also use primitive types (boolean instead of Boolean)where possible and adhere to Java naming conventions (camelCase).
ProgressDialog pausingDialog;
public void blockActivity(boolean connected)
{
if (pausingDialog == null){
pausingDialog = new ProgressDialog (this);
pausingDialog.setMessage ("Application waiting for internet connection...");
}
if (!connected)
{
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
pausingDialog.show();
pausingDialog.setCancelable(false);
}
else
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
pausingDialog.setCancelable(true);
pausingDialog.dismiss();
}
}
Simple Code In Kotlin
var pausingDialog:SweetAlertDialog?=null
fun blockActivity(connected: Boolean,context: Context) {
if (pausingDialog == null) {
pausingDialog =SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
pausingDialog!!.titleText = "Application waiting for internet connection..."
pausingDialog!!.setCancelable(false)
pausingDialog!!.setConfirmClickListener{
var MyReceiver: BroadcastReceiver?= null;
MyReceiver = com.example.myrecharge.Helper.MyReceiver()
context.registerReceiver(MyReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
}
if (!connected) {
Toast.makeText(
context,
"Disconnected",
Toast.LENGTH_LONG
).show()
pausingDialog!!.show()
Log.d("##", "onReceive: 1")
} else {
Toast.makeText(
context,
"Connected",
Toast.LENGTH_LONG
).show()
pausingDialog!!.dismiss()
}
}
Related
I would like to set my own activity infront the call screen. I have seen that there are many examples for this but with the older versions of android, while I want it to work with android 6.0 and above. This means that I have to deal with the permissions. I managed to grant the necessary permissions. After that I make a Class that inherits BroadcastReceiver so that I can detect when the phone is ringing, the only problem is that I can't send my activity infront of the call display. These are some of the classes I use:
public class PhoneStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Toast.makeText(context, " Receiver start ", Toast.LENGTH_SHORT).show();
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Toast.makeText(context, "Ringing State Number is -", Toast.LENGTH_SHORT).show();
Intent dialogIntent = new Intent(context, LockActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
context.startActivity(dialogIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LockActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lock_screen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+ WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
+WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
+WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
Button btnLock = (Button) findViewById(R.id.btnUnlock);
final EditText txtPass = (EditText) findViewById(R.id.txtPass);
btnLock.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String pass = txtPass.getText().toString();
if(pass.equals("pass")||pass.equals("пасс")) {
finish();
}else{
Toast.makeText(LockActivity.this, "Wrong password!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
If anything else is needed please ask!
I managed to solve it, the problem is that it takes time to start the in-built call activity, so my activity started first and the other went on top of it. Therefore I made the current thread of my activity to sleep for less than a second. The in-built activity was launched and then my activity went on top of it.
public class PhoneStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Toast.makeText(context, " Receiver start ", Toast.LENGTH_SHORT).show();
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Toast.makeText(context, "Ringing State Number is -", Toast.LENGTH_SHORT).show();
Intent dialogIntent = new Intent(context, LockActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Thread.sleep(700);
context.startActivity(dialogIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm building a android app that using connection with Java server (on computer).
I have a problem- when I find that there is no connection with the server, I'm trying to reconnect to the server but it doesn't work.
Here is the Client class code:
public class Client extends AsyncTask {
private final int port = 1978;
private final String ip = "192.168.14.22";
private Socket socket;
private DataOutputStream output;
private DataInputStream input;
public Client() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
socket = new Socket(ip, port);
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
Log.d("Network c1", "Connected");
} catch (IOException e) {
socket = null;
Log.d("Network c1", "Not connected");
}
return null;
}
public boolean checkConnection() {
if (output == null)
return false;
try {
output.writeUTF("abc");
return true;
} catch (IOException e) {
return false;
}
}
#Override
protected void onProgressUpdate(Object[] values) {
}
}
And the Activity code:
public class LogInActivity extends AppCompatActivity {
Client client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
client = new Client();
client.execute();
//I used timer because it didn't work without it- That saied always 'not connected' message/Toast
new CountDownTimer(5, 0) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
check();
}
}.start();
}
private void check() {
boolean isProcess;
isProcess = !checkConnection();
if (isProcess) {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert);
builder.setTitle(getResources().getString(R.string.app_name));
builder.setMessage("Unable connect to the library");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//See note 1.
check();
}
});
builder.setCancelable(false);
builder.show();
}
}
public boolean checkConnection() {
if (client.checkConnection()) {
Toast.makeText(getApplicationContext(), "Connected to the library", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Unable connect to the library", Toast.LENGTH_SHORT).show();
return false;
}
}
}
Note 1:
The problem is here.
This Dialog need to be shown until the server/Library connected.
If the server is on before the app turned on, the check() method works well and says 'Connected successful' and the Dialog doesn't show.
But if when the app started, the server was unreachable, and turned on later (And became reachable)- the check() method don't work and always shows the Dialog.
What is the problem?
By the way, I tried to restart the client AsyncTask Class, but i didn't succeed.
(I tried to do close(true) to it, and after do excute() to it again, but the cancel() method didn't worked, and was a error that said that after a AsyncTask Class excuted, it can't excute again)
Thanks.
You should not check for connectivity periodically (every couple of seconds like you do in this code).
Instead you should let the OS do this for you, it will be more reliable and more efficient in terms of battery and CPU.
Take a look at this answer
I am using following UsbSerial example from below link https://github.com/felHR85/SerialPortExample. I want receive data from over usb from the device shown in the photo.
Device is basically a counter machine which is sending counter data over serial port.
I am able to connect device and open port from it but unable to read data stream from it. Below is the code used. code is not giving any error
Mainactivity class
public class MainActivity extends AppCompatActivity {
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
private TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
display = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
Button sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("")) {
String data = editText.getText().toString();
if (usbService != null) { // if UsbService was correctly binded, Send data
display.append(data);
usbService.write(data.getBytes());
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
mActivity.get().display.append("Handle:");
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().display.append(data);
break;
}
}
}
}
I know it's bit late, however just to help others who might come across similar issue, did you find solution to your problem? If not, I cannot see the other java file corresponding to the service (USBService.java) as described in the example referred by you. The same file contains following code snippet which you would like to debug to find out what's going wrong (could be a problem with byte to string conversion or so). Hope this helps.
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback()
{
#Override
public void onReceivedData(byte[] arg0)
{
try
{
String data = new String(arg0, "UTF-8");
if(mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT,data).sendToTarget();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
};
i have created one simple login application which takes user name and password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using asyntask...
but i am unaware to use parameters in asyntask...if some one plzz tell me how to put my method in doInbackground of asyntask and what param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground() of asyntask...
making a fast refactorization (note that this as it stand it's really bad practice and coding, you MUST refactor this code to be more maintanable and to avoid duplication):
public class MyAsyncTask extends AsyncTask<> {
private Activity activity;
boolean result;
private String myLog;
private String myPass;
private Connection connect;
public MyAsyncTask(Activity activity, Connection connect) {
this.activity = activity;
this.connect = connect;
}
#Override
protected void onPreExecute() {
//show your progress dialog
}
#Override
protected Object doInBackground(Object[] objects) {
ResultSet rs = null;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
initilize();
mylog=id.getText().toString();
mypass=pass.getText().toString();
}
});
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
}
});
} else
try {
if(rs.next()){
result = true;
}
else if(rs.next()==false){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
});
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
//hide your progress dialog
if(result == Boolean.TRUE){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i=new Intent(activity.getApplicationContext(),Act2.class);
activity.startActivity(i);
}
});
}
}
}
then in your Activity you do this:
MyAsyncTask a = new MyAsyncTask(this, connect); //im guessing "connect" is your Connection object
a.execute();
As i said i made this fast refactoring for the code to work but best practice and good implementation is not in consideration here.
Maybe, you could use a timer, to check if your
login is ready. As long as it is not, you Show your progress Bar. If its ready, you can close the Bar and start a new activity or anything. timers run can run on u UI thread.
regards :)
I am using AsyncTask like this
public class AccountReportActivity extends Activity {
private OrgaLevelTask orgaLevelTask;
public void onCreate(Bundle savedInstanceState) {
......
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of onCreate
} //end of class AccountReportActivity
task:
public class OrgaLevelTask extends AsyncTask<Void, Void, ArrayList<OrgaLevel>> {
//Constrcutor
public OrgaLevelTask(AccountReportActivity accountReportActivity, Spinner spinner_orgaLevel, Spinner spinner_branch, TextView txt_extra, TextView txt_extra1) {
this.accountReportActivity = accountReportActivity;
this.spinner_orgaLevel = spinner_orgaLevel;
....
} //end of constructor
#Override
protected ArrayList<OrgaLevel> doInBackground(Void... arg0) {
return callWebService();
} //end of doInBackground()
private ArrayList<OrgaLevel> callWebService() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
......
} catch (SocketTimeoutException e) {
Toast.makeText(accountReportActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
return null;
} catch(Exception e) {
e.printStackTrace();
System.out.println();
}
} //end of callWebService()
} //end of class OrgaLevelTask
My this task call another AsyncTask which has the same code. The problem is if server is running then everything fine. But if server is not running and i call the web service then i get the exception that Force Application close. Why? I am handling SocketTimeoutException IF exception happens then i am saying that show toast on my Activity but why it is force closing the application. How can i handle it? Thanks
You can check the internet connection this way first
public static boolean checkConnection(Context context) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else
return false;
}
In this method
// Checking the internet connection
if (!InternetConnectionCheck.checkConnection(this)) {
Utilities.alertDialogBox(this, R.string.Title_String,
R.string.No_Internet_connection_String);
} else {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
}
you should not use use Toast in doInBackground
catch (SocketTimeoutException e) {
Toast.makeText(accountReportActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show(); //<----------------------