简体   繁体   中英

How to keep my application service always running in android2.1?

Hi i have written reminder code in service onstart().and when user insert date-time and insert record at that time service called by startservice() function,but only service is starting when i insert record ie i am getting reminder when it get call from my activity.but i want reminder after 3days or something so how should i keep service always on so that i can get reminder in future? or how should i make connection of service keep alive?should i called bindservice() frunction from my any activity or what? thanks in advance---

Don't let your Service run all the time. It consumes battery and memory when not neccessary¹. Rather schedule a PendingIntent via the AlarmManager thats starts the service at the relevant point in time to do it's work. When done, kill the service again.

In general androids services are used different then services/daemons on a "normal" computer. They have a task that they execute, then they quit (usually via Service.stopSelf() ) until someone starts them again to do more work.

Here is a small example how the AlarmManager is used:

// get a calendar with the current time
Calendar cal = Calendar.getInstance();
// add 15 minutes to the calendar object
cal.add(Calendar.MINUTE, 15);

Intent intent = new Intent(ctx, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 123, intent, 
                                            PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);

This launches the intent to start YourService in 15 minutes from now. There is plenty of documentation for sending intents this way, search a bit around.

¹ Which will eventually frustrate your users: "Why does this app waste my battery?" is a pretty common question

Sometimes, it may be necessary for your android app to complete a task sometime in the future. In order to do this, you must schedule an activity (can also be a service) to be run using Android's AlarmManager. This post will show:

* How to set up a receiver for the scheduled event
* How to create an activity from this receiver
* Using the AlarmManager and the created classes to successfully receive and process a scheduled event

Creating a BroadcastReceiver

The first thing you will need is a receiver to receive the event. There are several key aspects to have for the receiver to work properly. First create a class that extends BroadcastReceiver and override and implement the necessary onReceive(Context context, Intent intent) method. The following is a basic example using a Toast message:

package com.justcallmebrian.alarmexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import android.os.Bundle;

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
  try {
   Bundle bundle = intent.getExtras();
   String message = bundle.getString("alarm_message");
   Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
  Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
    e.printStackTrace();

   }
 }

}

In the previous example, we are simply just printing out the message supplied by the String passed in under the name of alarm_message. For those who are not familiar with Toast, it is basically a short and quick message given to the user. Here you can find more information on Toast.

Besides actually creating the class to receive the event, you must also declare it within AndroidManifest.xml. The following is the line that should be added before the closing of the application tag (before ).

Basically this states that the class AlarmReceiver is available and will start a private process. Once that is done, your BroadcastReceiver is ready to go.

Setting up an Event using AlarmManager In order to receive an event, you obviously must schedule the event. There are three ways of scheduling an event (a one time event using the set method, a repeating event using the setRepeating method and finally using the setInexactRepeating). This tutorial will cover the one time alarm using the set method. For more information regarding the other events, you can view AlarmManager.

The following code snippet will get the AlarmManager and set an event to occur 5 minutes from the current time:

 // get a Calendar object with current time
 Calendar cal = Calendar.getInstance();
 // add 5 minutes to the calendar object
 cal.add(Calendar.MINUTE, 5);
 Intent intent = new Intent(ctx, AlarmReceiver.class);
 intent.putExtra("alarm_message", "O'Doyle Rules!");
 // In reality, you would want to have a static variable for the request code instead of 192837
 PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 // Get the AlarmManager service
 AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
 am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

This code snippet basically obtains a new Calendar object and adds 5 minutes to it. An Intent is created with the AlarmReceiver which we created earlier. The more important piece of the code is setting the FLAG_UPDATE_CURRENT flag. Without this flag, the message being passed as an Extra will be lost and not obtained by the receiver.

With these code snippets you should be able to create and run some tasks in the BroadcastReceiver. However, sometimes you may wish to start a new activity (or service) on the alarm event. In order to do this, you would want to have the AlarmReceiver create and start the new Activity.

Starting an Activity from BroadcastReceiver Starting an activity within a Receiver has an extra flag that is needed. We will change the previous onReceive for AlarmReceiver to get this done:

@Override
public void onReceive(Context context, Intent intent) {
 try {
 Bundle bundle = intent.getExtras();
 String message = bundle.getString("alarm_message");

 Intent newIntent = new Intent(context, AlarmActivity.class);
 newIntent.putExtra("alarm_message", message);
 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 context.startActivity(newIntent);
 } catch (Exception e) {
 Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
 e.printStackTrace();

}
}

Now you would only have to create the new AlarmActivity as you would do any other Activity. Don't forget to include the newly created activity in the AndroidManifest.xml file.

Firstly no need of service,you can use AlarManagerClass Link Alarmanger class for schedule events and show alert at specific time and date. If you want show messages after some long duration then schedule a Pending-intent via the AlarmManager thats starts the service at the relevant point in time to do it's work. When done, kill the service again as per tell by above answers . In addition you can store your data into shared preferences for permanently. You can retrieve it at any time for resheulding it on device reboot or for other purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM