I want to make two android services that kip running on background even when my app is closed or when all system reboots, but I have no idea about android. And that's what I did:
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_ROOT_COMPLETED"/>
<service android:name="FirstService"></service>
<receiver android:name="FirstServiceReceiver">
<intent-filter>
<action android:name="com.android.techrainner"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="SecondService"></service>
<receiver android:name="SecondServiceReceiver">
<intent-filter>
<action android:name="com.android.techrainner"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
this my MainActivity (WL : because I am using IBM MobileFirst)
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
WL.createInstance(this);
WL.getInstance().showSplashScreen(this);
WL.getInstance().initializeWebFramework(getApplicationContext(), this);
Intent startFirstServiceIntent = new Intent(this,FirstService.class);
Intent startSecondServiceIntent = new Intent(this,SecondService.class);
startService(startFirstServiceIntent);
startService(startSecondServiceIntent);
}
this is the first service :
class FirstService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
return START_STICKY;
}
}
the second service is the same as the first
the first receiver :
public class FirstServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,FirstService.class));
}
}
Also the second receiver is the same as the first.
Two services are running on background only when the app is opened, and they will be stopped when I close it.
As in Android documentation, it is written about Service as:
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
So when operation is done Service stops automatically. If you want to start your service even your app gets destroyed then you can use Alarm Manager Service. You can set a repeating alarm in your application to start your service in background.
And if your requirement is to sync your app with your app server and want to sync with server even your app is closed then you can use SyncAdapter Framework of Android.
Related
I'm working on a music app, and I want stop the service when user removes the application from the recent list and not when the first activity is destroyed(because when user clicks back back until app minimizes, in that case first activity is also getting destroyed). Please help.
I want stop the service when user removes the application from the
recent list.
Yes, you can either do that using stopWithTask flag as true for Service in Manifest file.
Example:
<service
android:enabled="true"
android:name=".MyService"
android:exported="false"
android:stopWithTask="true" />
OR
If you need event of application being removed from recent list, and do something before stopping service, you can use this:
<service
android:enabled="true"
android:name=".MyService"
android:exported="false"
android:stopWithTask="false" />
So your service's method onTaskRemoved will be called. (Remember, it won't be called if you set stopWithTask to true).
public class MyService extends Service {
#Override
public void onStartService() {
//your code
}
#Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
//do something you want
//stop service
this.stopSelf();
}
}
Hope this helps.
The last answer didn't work for me (I am using API 29).
I looked up in the Javadoc of the onTaskRemoved function and saw the following instruction:
"If you have set {android:stopWithTask}, then you will not receive this callback; instead, the service will simply be stopped."
So, all I got to do is to remove this line (android:stopWithTask="false") from the manifest and it worked just fine.
This is the updated code in the manifest file:
<service
android:enabled="true"
android:name=".ExitService"
android:exported="false"/>
Im posting this answer, since the chosen as best solution was not working for me.
This is the updated version:
First create this service class:
public class ExitService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
//do something you want before app closes.
//stop service
this.stopSelf();
}
}
Then, declare this way your service in the manifest label:
<service
android:enabled="true"
android:name=".ExitService"
android:exported="false"
android:stopWithTask="false" />
Now, just start the service wherever you want to do something before your app closing.
Intent intent = new Intent(this, ExitService.class);
startService(intent);
I want to implement this scenario for my application. I want to schedule my service to start when the phone boots, and whenever another application calls my service I want my service to start a certain activity within the project.
So in order to be clear. I want to create a project which contains a service which runs whenever the phone boots, and is dormant, listening for a call from a third party application. And whenever that call is received this service calls an Activity (from the same project, not third party)
How can I configure my manifest file in order to achieve this?
I have also come across this suggestion but my scenario is pretty different.
Thank you very much in advance
**Define Service in manifest and Create the BroadcastReciever with boot complete permission and listen the intent.If boot completed start the service.**
public class MyService extends Service {
Context context = this;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Intent activity = new Intent(context, MyActivity.class);
activity.putExtra("Message", "fromService");
activity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(activity );
} catch (Exception e) {
MyLog.printException(e);
}
return super.onStartCommand(intent, flags, startId);
}
}
By creating a BroadcastReceiver you can perform the service startup.
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, ShowActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
and in the manifest
<receiver
android:name=".StartupReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
This allows you to run an Activity, you can then start a Foreground Service from that activity. I just set this example because I have it ready, you can adapt it to run a service as you like.
Im trying to track how many times the "SCREEN_ON" is triggered without the user starting the app. The app itself shows a single activity with some charts and info nothing more. I created a small test but i think it's not the correct way because it's draining my battery.
I got a broadcast receiver "BOOT_COMPLETED" that starts a sticky IntentService that is registering the "SCREEN_ON" broadcast receiver with a never ending loop to catch to broadcast's (the battery drain problem).
Is it possible that i can listen on the "SCREEN_ON" broadcast without a Service?
Jur
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".Application"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:hardwareAccelerated="true">
<activity
android:name=".activities.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".services.ScreenOnService" />
<receiver android:name=".broadcast.receivers.AutoStartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".broadcast.receivers.ScreenOnReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
</application>
AutoStartReceiver
public class AutoStartReceiver extends BroadcastReceiver
{
public void onReceive(Context aContext, Intent anIntent)
{
Log.i("[AutoStartReceiver]", "onReceive");
aContext.startService(new Intent(aContext, ScreenOnService.class));
}
}
ScreenOnReceiver
public class ScreenOnReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.i("[ScreenOnReceiver]", "onReceive");
}
}
ScreenOnService
public class ScreenOnService extends IntentService
{
private ScreenOnReceiver theReceiver;
public ScreenOnService()
{
super(ScreenOnService.class.getName());
theReceiver = new ScreenOnReceiver();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v("[ScreenOnService]", "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent)
{
Log.i("[ScreenOnService]", "onHandleIntent");
registerReceiver(theReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
while(true);
}
#Override
public void onDestroy()
{
Log.i("[ScreenOnService]", "onDestroy");
unregisterReceiver(theReceiver);
super.onDestroy();
}
}
Do you have any particular reason for using an IntentService as opposed to a regular started Service?
You should be able to achieve this using a regular started Service. Register the receiver as part of onStartCommand.
Something like this:
public class MyService extends Service {
private ScreenOnReceiver mReceiver;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mReceiver == null) {
mReceiver = new ScreenOnReceiver();
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
// remember to unregister receiver in onDestroy...
}
This way you avoid busy looping. IntentService is designed to be a short lived service performing a background operation. Your usage does not fit the purpose of IntentService.
I got a broadcast receiver "BOOT_COMPLETED" that starts a sticky IntentService that is registering the "SCREEN_ON" broadcast receiver with a never ending loop to catch to broadcast's (the battery drain problem)
This is completely inappropriate for an IntentService. Your problem is that an IntentService shuts down after onHandleIntent() returns, forcing you into this busy-wait.
Instead, use a regular Service.
Is it possible that i can listen on the "SCREEN_ON" broadcast without a Service?
AFAIK, ACTION_SCREEN_ON still cannot be registered for in the manifest, so, yes, you need a Service. But you need a Service, not an IntentService.
I got a broadcast receiver "BOOT_COMPLETED" that starts a sticky
IntentService that is registering the "SCREEN_ON" broadcast receiver
with a never ending loop to catch to broadcast's (the battery drain
problem).
This is not correct. The intent service is not design for long running operation.Actually It is no longer remain running after onHandleIntent().
If you want to listen constantly up to device is turn on then service will sure help you to listen each every trigger.
public class ScreenOnService extends Service
{
...........
}
I want to allow other Apps to integrate with mine and I'm writing a dummy "consumer" app but I cant achieve to return a callback to notify the "consumer" app if everything went well.
So my DUMMY_APP has a simple layout with 2 buttons a success call, and a call with a wrong EXTRA param.
To make DUMMY_APP to call MAIN_APP I use sendBroadcast
// MainActivity class
private static final String REQUIRED_ACTION = "com.basetis.afr.intent.action.INIT_TEXT_FLOW";
onCreate....
Button btnSuccess = (Button)findViewById(R.id.button_success_call);
btnSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i.setAction(REQUIRED_ACTION);
i.putExtra(Intent.EXTRA_TEXT, textToBeRead);
sendBroadcast(i);
}
});
So MAIN_APP has the corresponding BroadcastReceiver that is receiving fine.
// BlinkingReadReceiver class
private static final String CALLBACK_CALL_AFR_ACTION = "com.basetis.afr.intent.action.CALLBACK_CALL_AFR_ACTION";
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent();
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, "SUCCESS send callback");
i.setAction(CALLBACK_CALL_AFR_ACTION);
i.putExtra(CALL_AFR_SUCCESS_EXTRA, CALL_AFR_SUCCESS_EXTRA_DESC);
i.setType("text/plain");
context.sendBroadcast(i);
}
So the DUMMY_APP BroadcastReceiver never receive nothing :(
So I configured Manifests like that:
DUMMY_APP
<receiver android:name=".MainBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.basetis.afr.intent.action.CALLBACK_CALL_AFR_ACTION"></action>
</intent-filter>
</receiver>
MAIN_APP
<receiver android:name=".BlinkingReadReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.basetis.afr.intent.action.INIT_TEXT_FLOW"></action>
</intent-filter>
</receiver>
Sometimes I receive this error (afrsender is de DUMMY_APP) but seems sort of random...
Performing stop of activity that is not resumed: {com.basetis.afrsender.afrsender/com.basetis.afrsender.afrsender.MainActivity}
java.lang.RuntimeException: Performing stop of activity that is not resumed
Any suggestions about how to achieve this two way App communication?
Thank you very much.
As stated in the document
Starting from Android 3.1, the system's package manager keeps track of applications
that are in a stopped state and provides a means of controlling their launch from
background processes and other applications.
That means that till the app is not started manually by the user your app will be in force stop state and it won't receive any broadcast.
That's why your dummy app is not receiving and broadcast sent by main app.
Check here for more reference
Status:--- I equally accept Karakuri's and Sharad Mhaske's answer, but since Sharad Mhaske answer after the start of bounty, the bounty should go to him.
Part-2 made: part-2 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart
In stack overflow, only one answer may be accepted. I see both answers as acceptable but one has to be chosen (I chosed at random).
Viewers are invited to up/down vote answers/question to appreciate the effort!. I upvoted Karakuri's answer to compensate reputation.
Scenario:---
I want to make the user click a start/stop button and start/stop a service from UI activity. I have made the UI so dont care about that. But Just the logic of the Button click event.
Do not want the service to be bound to the UI activity. If activity closes, the service should keep running.
Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)
Unless the stop button is clicked by my apps UI, do not want it to be stopped (or should restart itself) Even if android reclaim memory. I and the user of the phone, both are/will be aware of it. The service is most of importance. Even at sleep.
details= my app do some operations, sleep for user provided time (15 minuts usually), wakes and perform operations again. this never ends)
If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?
When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.
QUESTION:---
Primary Question:
Just can't get an optimal strategy for the scenario... and also stuck on small bits of code, which one to use and how.
Gathered bits and pieces from stackoverflow.com questions, developer.android.com and some google results but cannot implement in integration.
Please read out the Requests Section.
Secondary Question:
The comments in my code are those small questions.
Research and Code:---
Strategy:
want this to happen every time the user opens the UI.
//Start Button:-----
//check if ForGroundService is running or not. if not running, make var/settings/etc "serviceStatus" as false
<-------(how and where to stare this and below stated boolean?)
//start ForGroundService
<-------(how?)
//make "SericeStatus" as true
//check if "ServiceStartOnBoot" is false
//Put ForGroundService to start on boot -------(to make it start when ever the phone reboots/restarts)
<-------(how?)
//make "ServiceStartOnBoot" as true
// the boolean can also be used to check the service status.
//Stop Button:------
//makes SericeStatus and ServiceStartOnBoot as false
//stops service and deletes the on boot entry/strategy
Activity UI class that starts/stops the service:
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//some button here to start / stop and their onClick Listners
Intent mySericeIntent = new Intent(this, TheService.class);
}
private void startMyForGroundService(){
startService(mySericeIntent);
}
private void stopMyForGroundSerice(){
stopService(mySericeIntent);
/////// is this a better approach?. stopService(new Intent(this, TheService.class));
/////// or making Intent mySericeIntent = new Intent(this, TheService.class);
/////// and making start and stop methods use the same?
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
The Service class:
public class TheService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1, new Notification());
////// will do all my stuff here on in the method onStart() or onCreat()?
return START_STICKY; ///// which return is better to keep the service running untill explicitly killed. contrary to system kill.
///// http://developer.android.com/reference/android/app/Service.html#START_FLAG_REDELIVERY
//notes:-// if you implement onStartCommand() to schedule work to be done asynchronously or in another thread,
//then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it
}
#Override
public void onDestroy() {
stop();
}
public void stop(){
//if running
// stop
// make vars as false
// do some stopping stuff
stopForeground(true);
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
The Menifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myapp.SettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
</application>
</manifest>
References:---
Android - implementing startForeground for a service? pointing answer 1, example code.
Trying to start a service on boot on Android
Android: Start Service on boot?
http://developer.android.com/guide/components/services.html
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/training/run-background-service/create-service.html not preffered by me.
http://developer.android.com/guide/components/processes-and-threads.html my starting point of research
Requests:---
I think this question is a normal practice for most people who are dealing with services.
In that vision, please only answer if you have experience in the scenario and can comprehensively explain the aspects and strategy with maximum sample code as a complete version so it would be a help to the community as well.
Vote up and down (with responsibility) to the answers as it matters to me who shared their views, time and experience and helped me and the community.
Que:Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)
Answer:you need to start service with using START_STICKY Intent flag.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Que:If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?
Answer:you need to register alarmmanager within service for the time after to some task.
//register alarm manager within service.
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);
//now have a broadcastreceiver to receive this intent.
class Alarmreceiver extends Broadcastreceiver
{
//u can to task in onreceive method of receiver.
}
//register this class in manifest for alarm receiver action.
Que:When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.
Answer:use broadcast reciver to listen for onboot completed intent.
public class StartAtBootServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
try {
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(), LicensingService.class.getName());
ComponentName service = context.startService(new Intent().setComponent(comp));
if (null == service){
// something really wrong here
//Log.Write("Could not start service " + comp.toString(),Log._LogLevel.NORAML);
}
}
else {
//Log.Write("Received unexpected intent " + intent.toString(),Log._LogLevel.NORAML);
}
} catch (Exception e) {
//Log.Write("Unexpected error occured in Licensing Server:" + e.toString(),Log._LogLevel.NORAML);
}
}
}
//need to register this receiver for Action_BOOTCOMPLETED intent in manifest.xml file
Hope this helps you clear out things :)
If you start a service with startService(), it will keep running even when the Activity closes. It will only be stopped when you call stopService(), or if it ever calls stopSelf() (or if the system kills your process to reclaim memory).
To start the service on boot, make a BroadcastReceiver that just starts the service:
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
Then add these to your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application ... >
<receiver android:name="MyReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Notice that the receiver is not enabled at first. When the user starts your service, use PackageManager to enable the receiver. When the user stops your service, use PackageManager to disable the receiver. In your Activity:
PackageManager pm = getPackageManager();
ComponentName receiver = new ComponentName(this, MyReceiver.class);
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Use same method with PackageManager.COMPONENT_ENABLED_STATE_DISABLED to disable it.
I have made something like this myself but I learned a lot while developing it and discovered it is not completely necesary to have the service running all day draining your battery. what I made is the following:
Implement a Service that reacts to events. In my particular I wanted to automate my Wifi and mobile data connection. so i react to events like wifi connecting and disconnecting, screen turning on and off, etc. So this service executes what ever needs to be executed responding to this event and then stops, scheduling any further actions with the AlarmManager if so needed.
now, this events can by timers like you said yourself every 15 minutes it does something and sleeps, that sounds to me that you really dont want the service running 24/7 but just executing something every 15 minutes. that is perfectly achievable with the AlarmManager without keeping your service running forever.
I recommend implementing this service deriving from commonsware's WakefulIntentService.
This class already handles the wakeLock for you so that you can exceute code even if phone is asleep. it will simply wakeup execute and go back to sleep.
Now. About your question regarding the activity starting and stoping the service. you can implement in the button that it starts or cancels the AlarmManager alarm. Also you can use the sharedPreferences to store a simple boolean that tells you if it is enabled or not so the next time your service runs it can read the value and know if it should continue or stop.
If you implement it as a event-reactive service as i said, your button can even react to broadcast intents so that your activity doesn't even have to call the service directly just broadcast an intent and the service can pick it like other events. use a BroadcastReceiver for this.
I'll try to give examples but be wary that what you're asking is a lot of code to put it in one place...
BootReceiver:
public class BootReceiver extends BroadcastReceiver
{
private static final String TAG = BootReceiver.class.getSimpleName();
#Override
public void onReceive(final Context context, final Intent intent)
{
final Intent in = new Intent(context, ActionHandlerService.class);
in.setAction(Actions.BOOT_RECEIVER_ACTION); //start the service with a flag telling the event that triggered
Log.i(TAG, "Boot completed. Starting service.");
WakedIntentService.sendWakefulWork(context, in);
}
}
Service:
public class ActionHandlerService extends WakedIntentService
{
private enum Action
{
WIFI_PULSE_ON, WIFI_PULSE_OFF, DATA_PULSE_ON, DATA_PULSE_OFF, SCREEN_ON, SCREEN_OFF, WIFI_CONNECTS, WIFI_DISCONNECTS, WIFI_CONNECT_TIMEOUT, WIFI_RECONNECT_TIMEOUT, START_UP, BOOT_UP
}
public ActionHandlerService()
{
super(ActionHandlerService.class.getName());
}
#Override
public void run(final Intent intent)
{
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettingsContainer.enabled = mSettings.getBoolean(getString(R.string.EnabledParameter), false);
if (intent != null)
{
final String action = intent.getAction();
if (action != null)
{
Log.i(TAG, "received action: " + action);
if (action.compareTo(Constants.Actions.SOME_EVENT) == 0)
{
//Do what ever you want
}
else
{
Log.w(TAG, "Unexpected action received: " + action);
}
}
else
{
Log.w(TAG, "Received null action!");
}
}
else
{
Log.w(TAG, "Received null intent!");
}
}
}
And your Manifest could go something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.yourcompany.yourapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="false"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourcompany.yourapp.activities.HomeActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.yourcompany.yourapp.services.ActionHandlerService" />
<receiver android:name="com.yourcompany.yourapp.receivers.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
</application>
</manifest>