Auto logout of application - android

I am trying to implement an auto logout functionality. If the application is not used for a period of 1 hour i would want to automatically bring the user to the login screen. When the phone gets locked the thread which is monitoring if the application is in use does not seem to continue. My code is as below:
/**
* This Deamon checks if the application is idle and
*/
private class LogoutDeamon extends Thread {
public void run() {
while (!logoutDeamon) {
try {
System.out.println("Logout Counter:" + logoutConter);
if (logoutConter <= 0) {
logoutDeamon = true;
ApplicationManager.getInstance().setLoggedOut(true);
ApplicationManager.getInstance().Log(Level.INFO, "Auto Log out");
logout();
} else {
decreamentCounter();
}
sleep(60000 * 1);
} catch (ParserException ex) {
Log(Level.ERROR, " Par. Ex. in Logout-Deamon:" + ex.getMessage());
logout();
} catch (ServerException ex) {
Log(Level.ERROR, " Ser. Ex. in Logout-Deamon:" + ex.getErrorMessage());
logout();
} catch (InterruptedException ie) {
Log(Level.ERROR, "Int. Ex. in Logout-Deamon:" + ie.getMessage());
} catch (Exception ex) {
Log(Level.ERROR, "Erro in Logout-Deamon:" + ex.getMessage());
logout();
}
}
}
private void logout(){
Intent broadcastIntent = new Intent();
broadcastIntent
.setAction("com.package.ACTION_LOGOUT");
applicationContext.sendBroadcast(broadcastIntent);
Intent loginIntent = new Intent(applicationContext,
Login.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
applicationContext.startActivity(loginIntent);
}
}
Am i missing out on something? Can someone kindly help me with this. Thanks in advance.

I don't think that you need a thread. Register the time in onPause. In onResume test if 1 hour has passed. If not, reset the timer.

Related

BluetoothDevice.ACTION_ACL_DISCONNECTED never called despite the bluetoothsocket is closed

I have two devices connected through Bluetooth now. After that, I disconnected the Bluetooth connection on the Client device, and the broadcast receiver in this Client device can detect the disconnection, and then switch it back to previous activity. Something like this:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
try {
Log.i("Disconnecting3", "Disconectinggg....");
Intent intent1 = new Intent(Main3Activity.this, MainActivity.class);
startActivity(intent1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
Anyhow, on my other device which is the Server device, this device CAN NOT detect the disconnection despite the Bluetooth socket is closed! The broadcast receiver in the Server device cannot detect the disconnection. FYI, below code will show how I close the Bluetooth socket on the Server device when the Client device is disconnected.
private boolean CONTINUE_READ_WRITE;
CONTINUE_READ_WRITE = true;
public void run() {
try {
while (CONTINUE_READ_WRITE) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = handleSeacrh.obtainMessage(MessageConstants.MESSAGE_READ, numBytes, -1, mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
//nothing();
CloseConnection closeConnection = new CloseConnection();
closeConnection.start();
break;
}
}
} catch (Exception e) {
// Log.d(TAG, "Input stream was disconnected", e);
}
}
public void cancel() {
try {
Log.i("TAG", "Trying to close the socket");
CONTINUE_READ_WRITE = false;
mBluetoothSocket.close();
mmBluetoothSocket.close();
Log.i("TAG", "I thinked its still closing");
} catch (IOException e) {
Log.e("TAG", "Could not close the connect socket", e);
}
}
So when there is a disconnection happened on the Client device, the while(CONTINUE_READ_WRITE)..loop will break the loop and start a new Thread. Something like this :
private class CloseConnection extends Thread {
public void run(){
Log.i("Running","Runinnggggg");
try {
mmInStream.close();
mmOutStream.close();
bluetoothDataTransmission.cancel();
Log.i("Interrupted","InteruppteDDDD");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Alright, I found a solution , just need to add this line of code
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

BroadcastReceiver is not listening the phone state - Unfortunately stopped when app is not in use

I have done the call recording in my application and am calling one Activity when the phone is in Ringing state.In that Activity just am showing the phone number and person name. For that I have written the code in my class which it extends BroadcastReceiver.
This scenario is working fine when I use the application. But If I close the application then am getting Unfortunately stopped
This is my AndroidManifest.xml.
<receiver android:name="com.domyhome.broadcastreceiver.IncomingCallInterceptor" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This is my onRecive method. When am using my application If i get a call then the current activity is not going to the background. So I have written the code to finish the Activity.
#Override
public void onReceive(Context context, Intent intent) {
LoginActivity.login.finish();
MainActivity.main.finish();
telephonyRegister(context,intent);
}
This is the functionality. I'am calling the ProjectDailogActivity when the phone state is Ringing. I'am finishing the same Activity when the call is attended or ended.
public void telephonyRegister(final Context context, Intent intent)
{
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
ctx=context;
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)) {
try
{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
if(ring==true&&callReceived==false)
{
Toast.makeText(context, "THIS IS MISSED CALL FROM"+phoneNumber, Toast.LENGTH_LONG).show();
String smsmessage = "Thanks for contacting us. We will get back you soon";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, "Dear Customer!"+" "+smsmessage, null, null);
Log.i("sms",smsmessage);
Toast.makeText(context, "SMS sent.",
Toast.LENGTH_LONG).show();
callReceived=false;
}
else if(callReceived==true)
{
try
{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
if(Conntact.isAvailable(phoneNumber))
{
try{
myAudioRecorder.release();
myAudioRecorder.stop();
myAudioRecorder = null;
}
catch(Exception e)
{
System.out.print("error");
}
Toast.makeText(context,"Recording Stopped", Toast.LENGTH_SHORT).show();
}
}
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK))
{
try{
ProjectDailogActivity.projdialog.finish();
}catch(Exception e)
{
e.printStackTrace();
}
dir = Environment.getExternalStorageDirectory();
try {
file = File.createTempFile("sound", ".mp3", dir);
} catch (IOException e) {
e.printStackTrace();
return;
}
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(file.getAbsolutePath());
if(Conntact.isAvailable(phoneNumber))
{
callReceived = true;
ring=false;
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "recording started", Toast.LENGTH_SHORT).show();
}
else
{
}
}
else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)){
phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
ring = true;
System.out.println("phonenum"+Conntact.isAvailable(phoneNumber));
if(!Conntact.isAvailable(phoneNumber))
{
Toast.makeText(ctx, phoneNumber+"not available", Toast.LENGTH_SHORT).show();
}
else if(Conntact.isAvailable(phoneNumber))
{
Intent intent11 = new Intent(ctx,ProjectDailogActivity.class);
intent11.putExtra("incoming_number",phoneNumber);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent11);
}
}
}
Conntact is a table where already some numbers has been stored. So when I get a call just am checking whether the calling number is available in the Conntact table.
If it is available then show the ProjectDailogActivity. If the number is available and the call is also picked means then do the recording. Everything is working fine . But it shows Unfortunately stopped when my app is not in use.
Consider unregistering for broadcast events while quitting from your app,Click here for a SO answer on same issue

Killing Android app 2 from app 1

I have 3 android apps. If a user has app1 open, is should check to see if app2, and/or app3 are running, and if so, kill them.
Here is what I have tried.
Implemented a BroadcastReceiver() in each app.
mFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("intent", "Got Kill Intent, I am " + pn);
if (killAction.equals(intent.getAction())) {
killmePlease(pn, killAction);
}
}
};
registerReceiver(mFinishReceiver, intentFilter);
and then, using this I try to kill the app..
private void killmePlease(String pn) {
Intent _killme = new Intent(this, MainActivity.class);
startActivity(_killme);
try {
Log.v("intent", "Finishing " + pn);
setResult(RESULT_OK);
MainActivity.this.finish();
System.exit(0);
Log.v("intent", "Finished");
return;
} catch (Exception ex) {
Log.v("intent", "Error Killing " + ex.getMessage());
}
}
However, the apps are still running with no errors thrown. Can anyone kindly tell me what I am missing?

Android: Intermitent application flow issue

I'm facing with an intermittent application flow issue.
Here, I've got a Login screen where I'm able to login for the first time. But when I'm logging out and/or re-loging in, I'm unable to traverse further. As a work around, I need to uninstall my application and reinstall it and the flow is ok.
Can anyone please guide me on the possible issue.
LoginActivity.java
GetWebServiceManager passwordExpiryWSManager = new GetWebServiceManager();
//to check network connectivity (data connection/Wi-Fi)
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInformation = connectionManager.getActiveNetworkInfo();
if (networkInformation != null && networkInformation.isConnected() == true) {
try {
// passwordExpiryString = passwordExpiryWSManager.execute("http://172.25.164.143:8088/api/Login/GetExpiredPassword/?lContactKey=" + username.getText().toString()).get();
passwordExpiryString = passwordExpiryWSManager.execute(AppConstants.URL + "/Login/GetExpiredPassword/?lContactKey=" + username.getText().toString()).get();
jsonObjectPassExpiry = new JSONObject(passwordExpiryString);
jsonArrayPassExpiry = jsonObjectPassExpiry.getJSONArray("LstLoginDetail");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Converting JSON string response from Webservice into Java Object
* */
if (jsonArrayPassExpiry != null) {
Gson gson = new Gson();
LoginTO[] loginExpTO = gson.fromJson(jsonArrayPassExpiry.toString(), LoginTO[].class);
loginListPassExpiry = Arrays.asList(loginExpTO);
intent = getIntent();
if (loginListPassExpiry.get(0).getlSuccess() == 1) {
intent.setClass(getApplicationContext(), PortfolioSummaryFragmentActivity.class);
// intent.putExtra("sToken", loginList.get(0).getsToken());
startActivity(intent);
} else {
intent.setClass(getApplicationContext(), PasswordExpiryActivity.class);
// intent.putExtra("sToken", loginList.get(0).getsToken());
startActivity(intent);
}
} else {
Toast.makeText(getApplicationContext(), "Service is not responding. Please try again later!!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Network connection unavailable. Please check your data plan or Wi-Fi connection!!", Toast.LENGTH_SHORT).show();
}
Logout.java
public class LogoutActivity extends Activity {
private TextView successResponse;
private Intent intent;
private Button btnLLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logout_success);
successResponse = (TextView) findViewById(R.id.txtvwLSuccessMessage);
btnLLogin = (Button) findViewById(R.id.btnLLogin);
intent = getIntent();
successResponse.setText(intent.getStringExtra("successResponse"));
}
public void Login(View v) {
btnLLogin.setTextColor(getResources().getColor(R.color.black));
intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onBackPressed() {
finish();
}
}
please use intent = new Intent(LogoutActivity.this, LoginActivity.class); instead of intent = new Intent(this, LoginActivity.class);
beside this use
most important
Add android:launchMode="singleTask " to the activity element in your manifest for Activity LoginActivity

License Check Loop?

Maybe the code kind of shows what I'm attempting to do, so I'll start with that
private void getLicenseResults() {
if (licensed && didCheck == true) {
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"***.MAINACTIVITY");
startActivity(openStartingPoint);
finish();
}
}
};
timer.start();
}
if (didCheck == false) {
Toast.makeText(Splash.this, "Checking License, Please Wait",
Toast.LENGTH_LONG).show();
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
getLicenseResults();
Log.i("LICENSE", "re-checking");
}
}
};
timer.start();
}
}
I ran the license check without trying to loop it before, and it worked except if the checking took more than a couple seconds it skipped over the
if (licensed && didCheck == true)
and the activity just kind of stood and waited without launching my main activity (this check is on the splash screen).
So I want the "if didCheck = true" part to be called only after didCheck is in fact finally true. I'm sure there's an easy solution, but I'm self-taught and I have no experience with loops or callbacks(?).
Thank you for any help!
You are not setting didCheck to true in your second if statement before the call to getLicenseResults

Categories

Resources