hi
When my app get the ACTION_BOOT_COMPLETED it starts a service.
I would like to delay that for lets say 60sec.
Can i do that in the:
public class StartAtBootServiceReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
// Delay...60sec
}
}
use Timer() and TimerTask():
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//run your service
}
}, 60000);
When you receive the BOOT_COMPLETED intent you should use the AlarmManager to setup an pending intent that will fire after 60 seconds.
Related
I am tryiny to update my edittext in UI. I have a service from where I send a intent by clicking a button and update in the UI. Everything works fine. But I would like to send intent without button click.
What I tried was to put my Intent in a method and call it oncreate in service but even then it been just called once.
public class myService extends service {
onCreate{
sendMessage();
}
private void sendMessage(){
Intent intent = new Intent("com.example.app.SEND");
intent.putExtra("KEY", (String) Number);
sendBroadcast(intent);
}
When I do like this, I just send empty string which is not useful. And even then just once.
Can I send intent continously ? So that It updates my UI once it receives input ? Any possible way to do it ?
I would like to send intent every 5 seconds.
You can use TimerTask with IntentService for scheduled jobs.
ex:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
//some execution
}
};
timer.schedule(timerTask, 5000, 5000);
I have an Android project which is sending a Broadcast every second and am trying to figure out how to stop it after a click.
My broadcast code is:
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
stoptimertask(); //it is stopping broadcast for a second.
You can define two methods: one that start a Timer to send a broadcast every second and a second one that stop the Timer.
Timer timer;
private void startBroadcastLoop() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Send broadcast
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
}
},0,1000); // Send broadcast every second
}
private void stopBroadcastLoop() {
if(timer!=null){
timer.cancel();
timer = null;
}
}
And then on your button, call the right function according to the state of a boolean:
sendBroadcastBool = false;
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// If broadcast not sent yet
if (!sendBroadcastBool) {
startBroadcastLoop();
sendBroadcastBool = true;
}
else {
stopBroadcastLoop();
sendBroadcastBool = false;
}
}
});
Best
I am Referring this Application https://github.com/hzitoun/android-camera2-secret-picture-taker.
In this Application there are two classes(APictureCapturingService.java & PictureCapturingServiceImpl.java) that takes pictures without preview can these two classes be converted to Background Service that runs always never dies.
Is this possible to have camera capturing process as a background service if yes how to proceed?
I don't know how you are taking picture in your activity but i can guide you to run your app in background even your close your app and you can able to run your camera code in every second..
public class SampleService extends Service {
public SampleService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#Override
public int onStartCommand(final Intent inten, int flags, int startId) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
// Make use your method here..
}
});
}
}, 5000, 2000);
return super.onStartCommand(inten, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
}}
And you need to start the service form activity..
startService(new Intent(this, SampleService.class));
I have used this for monitoring the foreground app it will work..
I am building an application whereby the notification will ring at a specific time and after which disappear if it is left unattended for 15 minutes. It works when i plug in my device and runs the code. However, once i unplug my device and runs the app, the notification works but it does not disappear after 15 minutes if it is left unattended. Please advice me how should i run the app like how it does when the device is plug into the computer. Also, it should work when the app is killed.
FYI, i'm using notification, alarmmanager, broadcast receiver and intentservice. Below is the snippet of my codes.
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Notification(context, "Wifi Connection On");
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
public void Notification(final Context context, String message) {
// notification codes
}
}
BackgroundService.java
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
//countdown 15 minutes and cancel notification automatically
Timer timer=new Timer();
TimerTask task=new TimerTask() {
#Override
public void run() {
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancelAll();
}
};
timer.schedule(task, 900000);
}
}
Manifest.xml
<receiver android:name=".AlarmReceiver" android:process=":remote" />
<service android:name=".BackgroundService" />
Please provide me some suggestions. Thank you.
This service will run twice: first time it does nothing except rescheduling, second time it cancels notifications.
public class BackgroundService extends IntentService {
private static final int REQUEST_CODE = 42;
private static final String ACTION_CANCEL_NOTIFS = "CancelNotifications";
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null && ACTION_CANCEL_NOTIFS.equals(intent.getAction())) {
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationmanager.cancelAll();
}
else {
reschedule();
}
}
private void reschedule() {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 15);
final Intent serviceIntent = new Intent(this, getClass());
serviceIntent.setAction(ACTION_CANCEL_NOTIFS);
PendingIntent pendingIntent = PendingIntent.getService(this, REQUEST_CODE, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
Explanation:
In your code, I assume, you start your service with startService(new Intent(this, BackgroundService.class)). This intent is passed as a parameter in onHandleIntent(Intent), which means you can access it from inside your service.
Intent allows you to pass additional data, such as action (useful for IntentFilters) or extras. Because you haven't set any, the first time around the execution goes to the else branch of onHandleIntent() method. AlarmManager is then scheduled to run your service in 15 minutes with serviceIntent. Note serviceIntent.setAction(ACTION_CANCEL_NOTIFS). So the second time around the execution goes to the if branch and cancels notifications.
A better approach would be creating a pending intent right from inside your activity instead of starting a service with startService. That would make your service simpler and more cohesive.
Service only runs when CPU is awake. If CPU gets off, service will not run.
SO to make your service to be run if phone goes to sleep, you need to aquire wake lock.
BackgroundService class
public class BackgroundService extends IntentService {
private PowerManager.WakeLock wl;
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Partial lock permission");
wl.acquire();
//countdown 15 minutes and cancel notification automatically
Timer timer=new Timer();
TimerTask task=new TimerTask() {
#Override
public void run() {
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancelAll();
wl.release();
}
};
timer.schedule(task, 900000);
}
}
If this does work out, try to give below permission in Android Manifest file
<uses-permission android:name="android.permission.WAKE_LOCK" />
I want to run some task (fetching data from database) in background after 5 minutes interval. What should I use?
Please mind that Google ask you to run long operations on Service. Please read the articles below, to detech what service do you need (service, interservice)!
Intent Service going to shut down itself after the job is done.
To fire a service in every 5mins to do the job , you can combine with a timer, as suggested above.
Mind before continue: Service belongs to the same thread, where you create it. So when you are about to developer your service please use a new Thread to start it. If you forget to do it, your service going to belong to the UI thread, mean you are in a trouble....
read first:
http://developer.android.com/guide/components/services.html
developer guide:
http://developer.android.com/reference/android/app/Service.html
You can use TimerTask inside a service
Timer timer = new Timer();
timer.schedule( new YourTask(), 50000 );
Try this.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Do something
}
}, 0, 5000);
Use Async task:
pre Execute, do inBackground, Post Execute
With alarm Manager
Intent myIntent1 = new Intent(sign_in.this,MyNotificationService.class);
pendingintent2 = PendingIntent.getService(sign_in.this, 1,myIntent1, 1);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar1Notify = Calendar.getInstance();
calendar1Notify.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 20);
alarmManager1.set(AlarmManager.RTC_WAKEUP,calendar1Notify.getTimeInMillis(), pendingintent2);
long time = 300*1000;// 5 minutes repeat
alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1Notify.getTimeInMillis(),time,pendingintent2);
Add Permission in manifest
<service android:name="com.example.MyNotificationService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
you can use a timer task:
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doTask(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//your task(fetch data)
}
});
}};
t.schedule(scanTask, 300000, 300000);
}
You can use timer, it is not a problem but method within android do have some advantages
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}