How to wake up my App Periodically - android

I want to make an functionality, like reminder, in Android.
I want to start-up my app/activity, when it is not running, or its UI is invisible.
It is some-thing like same as reminder, that wakes ups the app at desired time.
I have not worked with any type of background task or service,
so I haven't any idea that what to do,
or what type of classes or demos should be studied by me?
Can any one give me some suggestions with demos or tutorials links.
Thanks, in advance.

Hi use the following code. This is service. By using pending Intent with alarm manager you can open your UI at your needed time.
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ScheduleCheckService extends Service{
private Timer timer;
final int REFRESH=0;
Context context;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
context=this;
//==============================================
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
void PendingIntentmethod()
{
Intent myIntent = new Intent(context, YOURCLASS.class);
pendingIntent = PendingIntent.getActivity(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
}
}
Start the service and stop the service when you want and also dont forget to register it in manifest file.

Have a look at the Android Service class.
http://developer.android.com/reference/android/app/Service.html
From this Service you can periodically start (using a TimerTask) an Intent to open your App or just set a Notification, from which the user can open the App with the desired Activity. I would prefer the second option, because he user doesn't want an Application just to be opened at some time.
Here is a simple Service Tutorial:
http://www.vogella.com/articles/AndroidServices/article.html

Related

Android Data Upload in fixed time interval

I have an Android application, which uploads data into web service using async tasks(P,Q,R) currently starting fired in button click. I have three tables(A,B,C) of data. Currently I upload Table A data in doInBackground in first async task(P), I call second async task(Q) in onPostExecute of first async task(P).In onPostExecute, I update my local tables with returned data and give some UI messages as well. while that functionality is existing, now I want to upload data in a fixed time interval(every 30 minutes) even though the application is closed. when the device is booting up/installing app/updating app, this process should be started.While uploading data, if the user opens the application, upload button should be disabled.I don't necessarily need a long running task that runs forever.
1.Do I need to use services instead async tasks?
and give me advice on this.
To Upload Data do as follow
I think you are pretty new to android, Rather than Asynctasks i think you should move to volley or retrofit which is very easy and very fast when compared to Asynctask
Do I need to use services instead async tasks
Since you need to upload data every 30 mins i suggest you move your code to a service within which you will upload data. Also since a service is used it will work when the app is closed also, as it runs in the background
Your Receiver class
import java.util.Timer;
import java.util.TimerTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class yourReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
int delay = 5000; // delay for 5 sec.5000
int period = 60000; // repeat every 1min.60000
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Intent serviceIntent = new Intent(context,UploadService.class);
context.startService(serviceIntent);
}
}, delay, period);
}
}
Your Service Class
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class UploadService extends Service {
MediaPlayer myPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.sun);
myPlayer.setLooping(false); // Set looping
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
serviceThread = new ServiceThread();
serviceThread.start();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
private class ServiceThread extends Thread {
#Override
public void run() {
synchronized(UploadService.class){
if(uploadStatus) {
uploadStatus = false;
uploadData();
uploadStatus =true;
}
}
}
}
}

Restarting a service in the onDestroy method

I have made an app in which a service runs in the background. But if the android system requires resources, it will stop the service. However I may still require my service to run.
Is it a bad practice to restart the service (if condition relevant to my app still holds true) in the onDestroy method of my service?
How can I make sure my service runs indefinitely (if condition relevant to my app still holds true)? Or atleast on high priority?
Probably the best you can do is use the START_STICKY flag, which tells Android to attempt to restart the service if it has stopped. Beyond that ensure that it consumes as few resources as possible, so that it is less likely to be destroyed.
Android prioritizes the UI over everything. Then processes that are related to the UI. Then processes that are consuming the least amount of resources. A Service runs in the background, so unless it has resources that are also in use on the UI or connected to the UI in some way, it should be a lower priority.
Also you cannot tell Android how to prioritize your Service (everyone would make theirs the "highest priority" right?). So it goes by how well you minimize the impact on overall resources - why kill 3 Services when it could kill 1 and regain all the resources it needs?
To help understand how to manage memory better: http://developer.android.com/training/articles/memory.html
set it START_STICKY. It Causes after killing service the service will restart again. it is my code :
android manifest :
<application
....
<service android:name=".UpdateService" />
</application>
service class :
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.....);
filter.addAction(Intent....);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
Log.i("log", "action Called");
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
receiver class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Log", "recevid");
}
}
in StartupActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context context = getApplicationContext();
Intent service = new Intent(context, UpdateService.class);
context.startService(service);
}

How can I do something after Elapsed Time in Android?

I am new in programming.
I want to turn off wifi after 2h (I know how to turn it off) in the background
I googled and found out, that the Elapsed Real Timer is needed for that. I have also find this code and implemented it (this is the only code I have in my class) This class is called when the user selects something from a spinner dropdown:
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Toast;
/**
* Wird aufgerufen, wenn eine Zeit von der dropdown liste gewählt wurde
*/
public class ElapsedRealtimeAlarm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, ElapsedRealtimeAlarm.class), 0);
long firstTime = SystemClock.elapsedRealtime(); // elapsedRealTime --> Zeit seitdem booten.
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime, 1*1000*3600*2, mAlarmSender); // 1*1000 --> 1s * 3600 --> 1h * 2 --> 2h
Toast.makeText(getApplicationContext(), "Das ist ein Text", Toast.LENGTH_SHORT).show();
}
}
Is the code until yet fine? And how can I turn wifi off after the elapsed timer?
And does this the elapsed timer only one time or is this like an interval?
Sorry for my english
Thanks
EDIT:
I did the steps, mentioned in the answer of "Deb" and it is still nothing happening
Here the code
Step 1: "Make a BroadcatReceiver extending WakefulBroadcastReceiver"
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.widget.Toast;
public class BroadCastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
new BackgroundService(); // Step 4
}
}
Step 2: Make a service extending IntentService Class
Step 3: In your service inside onHandleIntent() write your code for switching the wifi off or on.
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.view.View;
import android.widget.Toast;
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
} else {
wifiManager.setWifiEnabled(true);
}
}
Step 4: Now go back to your BroadcastReceiver class and there inside onReceive() call your service that you made in step 2 (the code is already in step 1)
Manifest file (receiver, service and permissions for wifi)
<manifest ..... ..... ....>
<application>
.....
<receiver android:name=".BroadCastReceiver" ></receiver>
<service android:name=".BackgroundService" android:exported="false"></service>
</application>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
</manifest>
EDIT 2
The class where I am executing startActivity(new Intent(SpinnerTimeOnItemSelectedListener.this, ElapsedRealtimeAlarm.class));
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
public class SpinnerTimeOnItemSelectedListener extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).toString().equals("Zeit auswählen") || parent.getItemAtPosition(position).toString().equals("Select Time")){
//onNothingSelected(parent);
;
} else if (parent.getItemAtPosition(position).toString().equals("30min")){
startActivity(new Intent(SpinnerTimeOnItemSelectedListener.this, ElapsedRealtimeAlarm.class));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Wenn es einen ElapsedRealTimeAlarm gibt, soll er gecancelt werden
// Ansonsten nichts
;
}
}
ElapsedRealtimeAlarm's onCreate()
public class ElapsedRealtimeAlarm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Toast.makeText(getBaseContext(), "ElapsedRealTimeAlarm wurde aufgerufen", Toast.LENGTH_SHORT).show(); // just to check, that he called this class
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, BroadCastReceiver.class), 0);
long firstTime = SystemClock.elapsedRealtime(); // elapsedRealTime --> Zeit seitdem booten.
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime+2000, 10, mAlarmSender);
}
}
Make a BroadcatReceiver extending WakefulBroadcastReceiver .
Make a service extending IntentService Class.
In your service inside onHandleIntent() write your code for switching the wifi off or on.
Now go back to your BroadcastReceiver class and there inside onReceive() call your service that you made in step 2.
Your line of code
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime, 1*1000*3600*2, mAlarmSender);
This is responsible for running an alarmmanager repeatedly after every 2hrs.But if u want the alarm manager to run only once replace am.setRepeating() with am.set().
Your Code
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, ElapsedRealtimeAlarm.class), 0);
Replace PendingIntent.getService with the PendingIntent.getBroadcast and pass the reference of your BroadcastReceiver class you made in step 1
NOTE :Do not forget to write the receiver and service in your manifest otherwise it won't work
Update:
Inside your BroadcastReceiver's onReceive() call the service like this
Intent service=new Intent(context,BackgroundService.class);
startWakefulService(context, service);
this will call the onHandleIntent().
Update 2:
Replace getBaseContext() with this and change the PendingIntent.getService as
Intent i=new Intent(this, BroadCastReceiver.class);
PendingIntent alarmIntent=PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Do the following it will usefull to you
Create a service that turn wifi & other operations
Create a broadcast receiver inside that onReceive method call the service
Create a pending intent and alarm for a time which you want ,when alarm time period eleapses then trigger the broadcast receiver.

launch activity from service when notification is clicked

I know, there are tons of these on here, but I've been trying solutions all day and haven't gotten anywhere.
Neither the example on google's docs, nor any of the 5 other ways I've found on here have worked for me at all.
As is the typical case, when I click the notification it closes the status bar and nothing new is shown onscreen.
I am creating the notification from a service and need the notification to trigger a new activity that has not yet been created.
I also will need a way to pass information to that activity via intent.
And yes... this is java for Android
What follows are the shattered remnants of my code.
package com.bobbb.hwk2;
import java.io.FileOutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.widget.Toast;
public class contactBackup extends Service
{
private NotificationManager nManager;
private static final int NOTIFY_ID = 1100;
#Override
public void onCreate()
{
super.onCreate();
String ns = Context.NOTIFICATION_SERVICE;
nManager = (NotificationManager)getSystemService(ns);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// inform user that service has started
Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show();
String data = lookUpContacts();
if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) )
{
Context context = getApplicationContext();
// create the statusbar notification
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
//nIntent.putExtra("data",data);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
}
}
#Override
public void onDestroy()
{
nManager.cancel(NOTIFY_ID);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
// function returns string containing information
// from contacts
public String lookUpContacts()
{
...
}
public boolean saveToSDCard(String fileName, String data)
{
...
}
}
I can only hope that whatever is causing my problem is something fixable and not more of the crazy glitches I've been getting with eclipse (which no one else seems to have ever seen >:U )
If you can help me solve this problem, please share.
If you can't help with this specific problem but feel obligated to say unrelated things about posting, styles, topics, or good practice, then DON'T
Thank you :D
Edit:
You're going to have to add a flag for FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is because you're launching from outside your app (from the system notification bar).
This is what happens when people overwork themselves. XD
The only reason none of the tutorials I tired worked is because I misspelled my activity name in the manifest.
Thanks for stopping by
Just add following in contactBackup(service class),
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
nIntent.putExtra("data",data);
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
then get value in contactViewer class,
as,
String s=getIntent().getStringExtra("data");

Android Service stopping without being told?

I am having a weird situation where a Service that is created is stopping - sometimes. I have a entry Activity A that starts a service using bindService
// if we now have an IP address then bind ourselves to the MessageService
bindService(new Intent(this, MessagingService.class),
onMessageService,
BIND_AUTO_CREATE);
The MessageService handles kicking of Read and Send threads to handle message traffic with the app. It basically handles polling for new messages at 1 second intervals using a StatusTask and it's timer using timer.scheduleAtFixedRate.
Activity A then kicks off another Activity B that displays info to the user. For some reason that I yet to figure out, most of the time when I press the home button, the polling stops and the Service seems to have stopped. Reslecting my app from the Home recent apps list or via a notification I post when not visible brings the Activity to the foreground, but the Service seems to be gone. Making this harder to debug, about 10-20% of the time everything works great and the Message Polling service keeps plugging away.
Should I be using startService instead? The only direct relationship that the second Activity B has with the Service is that registers itself as an observer of the Read thread in order to be notified about timeouts on Reads. I am not calling stopService anywhere in my code.
public class Testservice extends Service {
private static final String TAG = Testservice.class.getSimpleName();
public Timer timer;
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
_startService();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
t.cancel();
t = null;
}
public void yourfunction()
{
}
//this will invoke the function on everysecond basis so try it if it helpsa
public void _startService(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
yourfunction();
}
});
}};
t.schedule(scanTask, 1000L, 1000L);
}
if developing using eclipse ---> try this go to DDMS that will be in the Perspective Option in Menu bar ---> select Logcat and while you are running your application just try to repeat the sequence you just mentioned above and on pressing home button just look at what is the error if at all coming during that instance and post the error so that the specific reason could be understood
Regards,
Mistry Hardik
Starting a service with bbindService makes the service lifecycle tied to the bound activities. Once your activity unbinds from the service, the service dies.
a simple service demo class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "AlertService";
Button buttonStart, buttonStop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.servicedemo);
buttonStart = (Button) findViewById(R.id.btnStart);
buttonStop = (Button) findViewById(R.id.btnStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.btnStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, Testservice.class));
break;
case R.id.btnStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, Testservice.class));
break;
}
}
}

Categories

Resources