I have an application that i want to set session to application means when i logged in to app and not used for 30 minutes like app running in background or screen off then i want to directly show login screen.is there any solution.?
For managing the session you you have to store the data some where like SharedPrefrence. After that youcan use Handler as given below in your First Activity.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Clear the Shared prefrence here
//here you can start your Login Activity
}
}, 1000);// Change the time according to need
App running in background
First thing you need to start a thread from your application to check the currently running application, find out the application on top use the following code to do this
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
String currentRunningActivityPackageName = taskInfo.get(0).topActivity.getPackageName();
This will return the current running application package, compare it with your application package name. If the application is not matching start a timer, if the timer cross 30 minutes,you can log out of your application, if in mean time your application comes in foreground stop the timer.
Screen off
For screen of you can register a broadcast
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
So according to the intent received you can toggle the same timer.
Related
I have a dialog box that starts when any push notification arrives and it is of 30 seconds. It is working fine if the app is in foreground but if the app is in background, the main activity starts and dialog box has to appear with the left over timer. But here, I am able to show dialog box but the time again starts from 30 seconds which I don't want.
What I have tried so far:
1. In FirebaseMessagingService, I have set a broadcastReceiver to send broadcast to other activities to start dialog. It is working fine and sending broadcast to start activities. and when I click on notification, dialog box appears but not showing timer.
2. I have tried to use service to start timer and the service is starting but timer is not working.
3. I have created another broadcastReceiver in first broadcast Receiver to set time in dialogBox. This is working even in background but not updating the timer values.
4. Starting countdown timer in background on receiving push notification I have used this as well but in this how to update values.
if(event.equals(eventName)){
String remoteMessageDate = remoteMessage.getData().get(eventName).toString();
intent = new Intent(this, DashboardMapsActivity.class);
Gson gson = new Gson();
booking = gson.fromJson(remoteMessageDate, BookingResult.class);
sendAllocateBroadcast(AppConstants.INSTANCE.getRIDE_REQUEST(), booking);
intent.putExtra(AppConstants.INSTANCE.getRIDE_REQUEST(),booking);
Log.w(TAG, "setActions: "+ Calendar.getInstance().getTime().toLocaleString());
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
// intent.setFlags(Intent.FL);
String message = "You have new booking";
createNotification(message);
BroadcastReceiver
BroadcastReceiver rideRequestreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.hasExtra(AppConstants.INSTANCE.getRIDE_REQUEST()))
{
Toast.makeText(DashboardMapsActivity.this,"booking Received",Toast.LENGTH_SHORT).show();
booking = (BookingResult) intent.getSerializableExtra(AppConstants.INSTANCE.getRIDE_REQUEST());
countDownTimer(booking.getBooking().getBookingId());
setFCMNewRideDialogValue(booking);
}
}
};
CountDownTimer
private void countDownTimer(final Integer bookingId) {
Intent intent1 = new Intent(this, TimerService.class);
startService(intent1);
countDownTimer = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
// Log.w(TAG, "onTick: "+ TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished));
rideRequestDialog.setTimerValues(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished));
}
#Override
public void onFinish() {
// Log.w(TAG, "onFinish: timer finish " );
rideRequestDialog.rideDismiss();
rejectRide(bookingId);
}
}.start();
}
OnCreate
if (intent.hasExtra(AppConstants.INSTANCE.getRIDE_REQUEST())) {
booking = (BookingResult) intent.getSerializableExtra(AppConstants.INSTANCE.getRIDE_REQUEST());
if(!(rideRequestDialog.dialogShowing()))
{
setFCMNewRideDialogValue(booking);
}
} else {
// Do something else
}
I want to show the dialog box with working timer values
I have defined following action in MainActivity class after click some button.
mSynchronizeData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()){
String packageName = "com.veryfit2hr.second";
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
startActivity(intent);
SystemClock.sleep(15000);
}
}
});
When other app is opening I want to return to the previos application after defined 15 seconds delay? I tried with MainActivity.super.onBackPressed();
I didn't work. Any ideas?
You can call the finish() method on the new activity that is being launched, and time the 15s delay there. From the docs:
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().
If you own the new activity you can simply call finish() after the desired time after it is created. However if you do not, one solution would be to start your own activity after 15 seconds, on top of the previously launched activity.
I would recommend against this pattern in general as it could be very confusing for the user to be launched between apps seemingly at random - but here is an implementation that could work.
Instead of locking up the main thread by calling SystemClock.sleep(15000);, you'll want to schedule the call to happen after 15 seconds. We can use Handler for this.
Handler handler = new Handler(Looper.getMainLooper())
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = // Create intent for your activity here
startActivity(intent)
}
}, 15000);
I want a best consistent solution to call an api to update current location in every 2 minutes on Nougat and higher version. The process should not be terminated even when the app is killed or closed.
Thanks in advance
Create a services:
public class MyServices extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
startService(new Intent(this,MyServices.class));
Timer t = new Timer();
final Handler handler = new Handler();
// Timer task makes your service will repeat after every 20 Sec.
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//Do network call here
}
});
}
};
//Starts after 20 sec and will repeat on every 20 sec of time interval.
t.schedule(doAsynchronousTask, 3000,3000); // 20 sec timer
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
Register the service in menifest
<service android:name=".MyServices" />
Start the service in your activity
Intent intent = new Intent(this, MyServices.class);
startService(intent);
if version > N use this
startForegroundService(intent);
Create a service and update from there.
Service will not stop after closing the application but it will get stopped if the application is force stopped.
And also if your app goes to doze mode your app cannot use Internet or GPS service from the background.
You should check out WorkManager to schedule any kind of work you want your app to do.
In the Google's In App Billing example(Dungeons) there is a Service instance created in main Activity onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler = new Handler();
mDungeonsPurchaseObserver = new DungeonsPurchaseObserver(mHandler);
mBillingService = new BillingService();
mBillingService.setContext(this);
....
}
and in the receiver the service is started by the context.startService.
private void notify(Context context, String notifyId) {
Intent intent = new Intent(Consts.ACTION_GET_PURCHASE_INFORMATION);
intent.setClass(context, BillingService.class);
intent.putExtra(Consts.NOTIFICATION_ID, notifyId);
context.startService(intent);
}
Will notify use somehow the some instance created in onCreate or it will create another instance of this class running as an actual service?
What do you mean by "allways one instance"? Is that important?
As far as I know, when receiver get it, It starts the service and check the user has actually bought it (i.e. get purchase info). After the service has completed, it send a broadcast message to you, so that you can act accordingly. I don't think that it runs always in the background.
In my android application, I am using the tab view and so I have two tabs: parameters and results.
the user enters the various parameters on the first tab and then switches to the second tab to view the results.
i have a service that performs some long-running calculations. the user enters parameters on the first tab and hits 'calculate'. They can make adjustments and hit 'recalculate' and the service is updated with the new parameters.
As these calculations progress, I want the user to be able to switch to the results tab to view the results of the latest calculation. They would then view the results and be able to switch back to the parameters tab to make adjustments.
I can think of two approaches:
-register the 'results tab' with the service and when the service reaches a milestone, it calls directly to the 'results tab'.
-have a timer running in the 'results tab' and have it query against the bound service on a regular interval and update accordingly.
Do people have comments or recommendations for these two approaches?
AsyncTask has a publishProgress method that should make it really painless to push updates from your background task to the UI thread.
Using broadcast Receiver
public class Detail extends GDActivity {
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
mProgressDialog.setProgress(intent.getFlags());
}
}
};
// Flag if receiver is registered
private boolean mReceiversRegistered = false;
// Define a handler and a broadcast receiver
private final Handler mHandler = new Handler();
#Override
protected void onResume() {
super.onResume();
// Register Sync Recievers
IntentFilter intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
mReceiversRegistered = true;
}
#Override
public void onPause() {
super.onPause();
// Make sure you unregister your receivers when you pause your activity
if(mReceiversRegistered) {
unregisterReceiver(mIntentReceiver);
mReceiversRegistered = false;
}
}
}
}
and the Sender
#Override
protected void onProgressUpdate(Integer... progress) {
Intent i = new Intent();
i.setAction(CUSTOM_INTENT);
i.setFlags(progress[0]);
ctx.sendBroadcast(i);
}