I am new to Android.
I am having Accelerometer sensor data in one activity. I stopped the SensorManager after a shake has been detected. Now I need to restart the activity automatically after 5 seconds, the SensorManager has stopped. Is it possible?
or is it possible to start the current activity from the same?
Can somebody help me with this?
Thanks in Advance :)
I need to restart the activity automatically after 5 seconds, the
sensorManager has stopped. Is it possible?
Yes it is possible using AlarmManager
When stopping SensorManager provide PendingIntent of Activity to AlarmManager with required delay to start Activity:
Intent intent = new Intent(context,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC,System.currentTimeMillis() + 6000, pendingIntent);
Use this code when SensorManager has stopped. It will restart the Activity after 5 sec when SensorManager has stopped.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}, 5000);
When you stop Sensor, you can start Activity after 5s by use Handler like
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(...);
}
}, 5000);
Thread is used to provide delay.
Add the below code when your sensor stopped detected.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Start Activity here
}
},5000);
Related
I just start background service in Handler.now I want to stop Service but service not stopped from Handler and any other class.
below is My Code:-
below is handler where i try to Start And Stop Service.
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
Log.e("mTrackStatus",String.valueOf(mTrackStatus));
if (mTrackStatus == 1) {
Log.e("BACKGROUND=", "background Service Start");
//handler will call after every 10 seconds
context.startService(new Intent(context, BackgroundService.class));
mHandler.postDelayed(mRunnable, 10000);
} else if (mTrackStatus == 2) {
Log.d("StopTracking", "StopTracking");
context.stopService(new Intent(context, BackgroundService.class));
mHandler.removeCallbacks(mRunnable);
}
}
};
// mHandler.postDelayed(mRunnable, 10000);
mRunnable.run();
I have tried Lot's Of method like
1. context.stopService(new Intent(context,BackgroundService.class)); and stopSelf(); but it will not work for me
I have Spent 2 days on this problem. Finally i Solve the Issue.Actually My BackgrounService is Stop by using :-
context.stopService(new Intent(context, BackgroundService.class));
I use onLocationChanged() method in My services class and when i Try to Stop Service, Service is Stopped but onLocationChanged() method is Continue sly running in Background. By using Stop Service Service is stop but onLocationChanged() is not Stopped because it Android Default method which we can not able stop that.
I'm trying to get a process timer to run and keep it running in the background on android (starts with a button click).
The timer must be on 30 seconds and should even continue growing application in the background (with home button and power / screen off).
How can I do this? I tried with service and handler but not working ...
EDIT
My service tracking (process with 30 sec)
public class TrackingService extends IntentService {
private Handler mHandler;
private Runnable mRunnable;
public TrackingService() {
super("TrackingService");
}
public TrackingService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
long timer = 30000;
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
//TODO - process with update timer for new 30 sec
mHandler.postDelayed(this, timer);
}
};
mHandler.postDelayed(mRunnable, timer);
}
}
My click button:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO - start first time and it continued every 30 seconds and continue in the background
startService(Intent intent = new Intent(this, TrackingService.class));
}
});
Ok, first of all, I really don't know if I got your question quite right.
But I think you want a timer that's being executed every 30 seconds ,if i'm not mistaken.
If so, do as following:
AlarmManager
Note: This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.
Example:
in your onClick() register your timer:
int repeatTime = 30; //Repeat alarm time in seconds
AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, processTimerReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Repeat alarm every second
processTimer.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),repeatTime*1000, pendingIntent);
And your processTimerReceiver class:
//This is called every second (depends on repeatTime)
public class processTimerReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//Do something every 30 seconds
}
}
Don't forget to register your receiver in your Manifest.XML
<receiver android:name="processTimer" >
<intent-filter>
<action android:name="processTimerReceiver" >
</action>
</intent-filter>
</receiver>
If you ever want to cancel the alarm:
use this to do so:
//Cancel the alarm
Intent intent = new Intent(this, processTimerReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Hope this helps you out.
PS: if this is not exactly what u want, please leave it in the comments, or if someone wants to edit this, please do so.
Oh god, don't ever use AlarmManager for 30s timers. It's kind of an overkill and also put a significant drain on device resources (battery, CPU...).
Perhaps you could try using a real background Service instead of IntentService as IntentService tends to shut itself down when it runs out of work. Not sure if this is the case here, but it's worth a try.
how to create an activity that is restricted to time. I would like when I launch my app, an initial activity appears and lasts only for few seconds just to display the app name and the its version and some other info and after a the designated time, the app starts. I have done such thing but the initial activity had had an animation, and when the animation ends then the new activity or the app starts. But, now my initial activity has no animation and I do not know how to keep an activity active/live for 10 seconds, for an example, and when the 10 seconds end, another app starts?
Use a handler to wait (for example 3 seconds) and move on:
private static int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with timer running. This is useful to showcase your app logo/company or something like that.
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
You can use a Timer:
private Timer timer;
#Override
protected void onResume (){
super.onResume();
timer = new Timer();
timer.schedule(new OpenActivityTask(), SOME_TIME_IN_MILLIS);
}
#Override
protected void onPause (){
super. onPause();
timer.cancel();
timer = null;
}
private static class OpenActivityTask extends TimerTask {
#Override
public void run() {
//TODO Go to new activity
}
}
It provides cancellation in case you manually close the activity before the delay time is reached, or if it goes to background for some reason.
Another option is to use the AlarmManager and schedule a one-shot PendingIntent. This approach is probably shorter in code and also allows for safe cancellation:
PendingIntent pi;
#Override
protected void onResume (){
super.onResume();
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, YourOtherActivity.class);
pi = PendingIntent.getActivity(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + SOME_TIME_IN_MILLIS, pi);
}
#Override
protected void onPause (){
super. onPause();
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pi);
}
In my activity I have a private BroadcastReceiver, when triggered, should update the UI after some ms. In my Activity I have:
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("BroadCastReciever: ", "UpdateCaseList");
update.RefreshCaseList();
}
};
This BroadcastReceiver is beeing triggered from a Service:
#Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 0);
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
handler.postDelayed(this, 10000); // 10 seconds
sendUpdateToUiThread();
}
};
private void sendUpdateToUiThread() {
sendBroadcast(intent);
}
I guess that the onStart method is being called when I Register BroadcastReceiver in my OnResume() method. I also unregister the BroadcastReceiver in onPause.
My intention is that this should sent a notification to the Activity, every 10 seconds. Once I start the application, my service will notify the Activity every 10 seconds, as planned. The problem is when I leave the Activity and return back, it doesn't post a notification to the activity every 10 seconds, but just at a random time. I can see in LogCat that this randomness spamming occurs every 4, 6, 3, 8, 6 seconds and so on. Why on earth this behaviour?
According to postDelayed documentation
the Runnable is called after millisecods elapsed and
Time spent in deep sleep will add an additional delay to execution.
So some randomness is by design. So I would expect the Runnable called after more than 10000 ms in your case.
I was searching over the internet for last 2 days but I couldn't find any tutorial helpful. I have created a service and I am sending a notification in status bar when the service starts. I want that service to stop after showing the notification and start it again after 5 minutes. Please let me know if it is possible and provide me some helpful tutorials if you have any. I heard of TimerTask and AlarmManager and I tried to use them as well but I wasn't able to get the desired result.
EDIT: I need the service to be started every 5 minutes even if my application is not running.
You do not want to use a TimerTask since this depends on your application running continuously. An AlarmManager implementation makes it safe for your application to be killed between executions.
Stating that you tried to use AlarmManager but did not get the desired result is not a helpful statement, in that it tells no one how to help you to get it right. It would be much more useful to express what happened.
http://web.archive.org/web/20170713001201/http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ contains what appears to be a useful tutorial on AlarmManager. Here are the salient points:
1) Your alarm will cause an Intent to fire when it expires. It's up to you to decide what kind of Intent and how it should be implemented. The link I provided has a complete example based on a BroadcastReceiver.
2) You can install your alarm with an example such as:
public void setOnetimeTimer(Context context) {
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi);
}
Below I have provided three files, MainActivity.java for start service, Second file MyService.java providing service for 5 Minute and Third is manifest file.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class)); //start service which is MyService.java
}
}
MyService.java
public class MyService extends Service {
public static final int notify = 300000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
}
});
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:enabled="true" android:exported="true"></service>
Create a Timer object and give it a TimerTask that performs the code you'd like to perform.
Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
#Override
public void run () {
// your code here...
}
};
// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 every 10 minut
The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.