StartService method is executed but events of Service not fires - android

I have an activity which I start a service in the OnCreate method. StartService method is executed without any error, but none of the events in Service class are not fired!
I test both of the explicit and implicit modes to start the service as you can see in my code, but both results were same!
My codes:
Activity:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
serviceToStart = new Intent(ApplicationContext, typeof(TrackService));
StartService(serviceToStart);
}
catch(Exception e)
{
var ee = e;
}
}
Track Service:
[Service(IsolatedProcess = true, enabled = true)]
public class TrackService : Service
{
FusedLocationProviderClient fusedLocationProviderClient;
public override void OnCreate()
{
base.OnCreate(); //Break point set here
}
public override StartCommandResult OnStartCommand(Android.Content.Intent
intent, StartCommandFlags flags, int startId)
{
fusedLocationProviderClient =
LocationServices
.GetFusedLocationProviderClient(this); //Break point set here
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
Manifest:
EDIT: Manifest manuals removed removed
Can anyone say me what's the problem?

Please mention you service in the manifest file. This is very important step because without manifest service entry your service class never initiated.
Below line of code is very important, this should be in your manifest file.
<service android:name=".TrackService" android:enabled="true"></service>
Referrer to below link for more clarification about the services
- https://developer.android.com/training/run-background-service/create-service

1) Allow the ServiceAttribute (and the build process) to property set the manifest entry and no manual changes are needed:
[Service(IsolatedProcess = true, enabled = true)]
Note: If you wish/need to manually change the manifest, you will need to assign the Name in the ServiceAttribute to hard-code a fully-qualified package and Java class name that you can then use in your manifest
2) When starting the service, build an intent using the application context and the C# type of your service:
var serviceIntent = new Intent(ApplicationContext, typeof(TrackService));
StartService(serviceIntent);

Finally! I found the problem root! However, I don't know why it happens and how can I resolve it!
I always got this error in logcat:
No implementation found for void mono.android.Runtime.register
After removing part by part of the code I got that the problem is caused by IsolatedProcess attribute. Just by removing it the code works well.
Note: As you can see there's no need to put enabled attribute for service too.
[Service]
public class TrackService : Service

Related

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

On application launch, app starts the service that should to do some network task.
After targeting API level 26, my application fails to start service on Android 8.0 on background.
Caused by: java.lang.IllegalStateException: Not allowed to start
service Intent {
cmp=my.app.tt/com.my.service
}: app is in background uid UidRecord{90372b1 u0a136 CEM idle procs:1
seq(0,0,0)}
as I understand it related to:
Background execution limits
The startService() method now throws an IllegalStateException if an
app targeting Android 8.0 tries to use that method in a situation when
it isn't permitted to create background services.
"in a situation when it isn't permitted" - what it's actually mean?? And how to fix it. I don't want to set my service as "foreground"
I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, ServedService.class));
} else {
context.startService(new Intent(context, ServedService.class));
}
And in service class, please add the code below for notification:
#Override
public void onCreate() {
super.onCreate();
startForeground(1,new Notification());
}
Where O is Android version 26.
If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:
Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
//retrieve an instance of the service here from the IBinder returned
//from the onBind method to communicate with
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
}, Context.BIND_AUTO_CREATE);
The permitted situations are a temporary whitelist where the background service behaves the same as before Android O.
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:
Handling a high-priority Firebase Cloud Messaging (FCM) message.
Receiving a broadcast, such as an SMS/MMS message.
Executing a PendingIntent from a notification.
Starting a VpnService before the VPN app promotes itself to the foreground.
Source: https://developer.android.com/about/versions/oreo/background.html
So in other words if your background service does not meet the whitelist requirements you have to use the new JobScheduler. It's basically the same as a background service, but it gets called periodically instead of running in the background continuously.
If you're using an IntentService, you can change to a JobIntentService. See #kosev's answer below.
The best way is to use JobIntentService which uses the new JobScheduler for Oreo or the old services if not available.
Declare in your manifest:
<service android:name=".YourService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
And in your service you have to replace onHandleIntent with onHandleWork:
public class YourService extends JobIntentService {
public static final int JOB_ID = 1;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, YourService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
// your code
}
}
Then you start your service with:
YourService.enqueueWork(context, new Intent());
If the service is running in a background thread by extending IntentService, you can replace IntentService with JobIntentService which is provided as part of Android Support Library
The advantage of using JobIntentService is, it behaves as an IntentService on pre-O devices and on O and higher, it dispatches it as a job
JobScheduler can also be used for periodic/on demand jobs. But, ensure to handle backward compatibility as JobScheduler API is available only from API 21
Yeah, that's because you can't start services in the background anymore on API 26. So you can start ForegroundService above API 26.
You'll have to use
ContextCompat.startForegroundService(...)
and post a notification while processing the leak.
As #kosev said in his answer you can use JobIntentService.
But I use an alternative solution - I catch IllegalStateException and start the service as foreground.
For example, this function starts my service:
#JvmStatic
protected fun startService(intentAction: String, serviceType: Class<*>, intentExtraSetup: (Intent) -> Unit) {
val context = App.context
val intent = Intent(context, serviceType)
intent.action = intentAction
intentExtraSetup(intent)
intent.putExtra(NEED_FOREGROUND_KEY, false)
try {
context.startService(intent)
}
catch (ex: IllegalStateException) {
intent.putExtra(NEED_FOREGROUND_KEY, true)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
}
else {
context.startService(intent)
}
}
}
and when I process Intent I do such thing:
override fun onHandleIntent(intent: Intent?) {
val needToMoveToForeground = intent?.getBooleanExtra(NEED_FOREGROUND_KEY, false) ?: false
if(needToMoveToForeground) {
val notification = notificationService.createSyncServiceNotification()
startForeground(notification.second, notification.first)
isInForeground = true
}
intent?.let {
getTask(it)?.process()
}
}
I see a lot of responses that recommend just using a ForegroundService. In order to use a ForegroundService there has to be a notification associated with it. Users will see this notification. Depending on the situation, they may become annoyed with your app and uninstall it.
The easiest solution is to use the new Architecture Component called WorkManager. You can check out the documentation here: https://developer.android.com/topic/libraries/architecture/workmanager/
You just define your worker class that extends Worker.
public class CompressWorker extends Worker {
public CompressWorker(
#NonNull Context context,
#NonNull WorkerParameters params) {
super(context, params);
}
#Override
public Worker.Result doWork() {
// Do the work here--in this case, compress the stored images.
// In this example no parameters are passed; the task is
// assumed to be "compress the whole library."
myCompress();
// Indicate success or failure with your return value:
return Result.SUCCESS;
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
Then you schedule when you want to run it.
OneTimeWorkRequest compressionWork =
new OneTimeWorkRequest.Builder(CompressWorker.class)
.build();
WorkManager.getInstance().enqueue(compressionWork);
Easy! There are a lot of ways you can configure workers. It supports recurring jobs and you can even do complex stuff like chaining if you need it. Hope this helps.
Alternate solution by using JobScheduler, it can start service in background in regular interval of time.
Firstly make class named as Util.java
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
public class Util {
// schedule the start of the service every 10 - 30 seconds
public static void schedulerJob(Context context) {
ComponentName serviceComponent = new ComponentName(context,TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0,serviceComponent);
builder.setMinimumLatency(1*1000); // wait at least
builder.setOverrideDeadline(3*1000); //delay time
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
builder.setRequiresCharging(false); // we don't care if the device is charging or not
builder.setRequiresDeviceIdle(true); // device should be idle
System.out.println("(scheduler Job");
JobScheduler jobScheduler = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
jobScheduler = context.getSystemService(JobScheduler.class);
}
jobScheduler.schedule(builder.build());
}
}
Then, make JobService class named as TestJobService.java
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.widget.Toast;
/**
* JobService to be scheduled by the JobScheduler.
* start another service
*/
public class TestJobService extends JobService {
#Override
public boolean onStartJob(JobParameters params) {
Util.schedulerJob(getApplicationContext()); // reschedule the job
Toast.makeText(this, "Bg Service", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
After that BroadCast Receiver class named ServiceReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Util.schedulerJob(context);
}
}
Update Manifest file with service and receiver class code
<receiver android:name=".ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".TestJobService"
android:label="Word service"
android:permission="android.permission.BIND_JOB_SERVICE" >
</service>
Left main_intent launcher to mainActivity.java file which is created by default, and changes in MainActivity.java file are
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Util.schedulerJob(getApplicationContext());
}
}
WOOAAH!! Background Service starts without Foreground service
[Edit]: You can use Work Manager for any type of background tasks in Android.
From the firebase release notes, they state that support for Android O was first released in 10.2.1 (although I'd recommend using the most recent version).
please add new firebase messaging dependencies for android O
compile 'com.google.firebase:firebase-messaging:11.6.2'
upgrade google play services and google repositories if needed.
If any intent was previously working fine when the app is in the background, it won't be the case any more from Android 8 and above. Only referring to intent which has to do some processing when app is in the background.
The below steps have to be followed:
Above mentioned intent should be using JobIntentService instead of
IntentService.
The class which extends JobIntentService should implement the - onHandleWork(#NonNull Intent intent) method and should have below the
method, which will invoke the onHandleWork method:
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, xyz.class, 123, work);
}
Call enqueueWork(Context, intent) from the class where your intent is defined.
Sample code:
Public class A {
...
...
Intent intent = new Intent(Context, B.class);
//startService(intent);
B.enqueueWork(Context, intent);
}
The below class was previously extending the Service class
Public Class B extends JobIntentService{
...
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, B.class, JobId, work);
}
protected void onHandleWork(#NonNull Intent intent) {
...
...
}
}
com.android.support:support-compat is needed for JobIntentService - I use 26.1.0 V.
Most important is to ensure the Firebase libraries version is on at least 10.2.1, I had issues with 10.2.0 - if you have any!
Your manifest should have the below permission for the Service class:
service android:name=".B"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE"
Hope this helps.
If you are running your code on 8.0 then application will crash. So start the service in the foreground. If below 8.0 use this :
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
context.startService(serviceIntent);
If above or 8.0 then use this :
Intent serviceIntent = new Intent(context, RingtonePlayingService.class);
ContextCompat.startForegroundService(context, serviceIntent );
Due to controversial votes on this answer (+4/-4 as of this edit), PLEASE LOOK AT THE OTHER ANSWERS FIRST AND USE THIS ONLY AS A LAST RESORT. I only used this once for a networking app that runs as root and I agree with the general opinion that this solution should not be used under normal circumstances.
Original answer below:
The other answers are all correct, but I'd like to point out that another way to get around this is to ask user to disable battery optimizations for your app (this isn't usually a good idea unless your app is system related). See this answer for how to request to opt out of battery optimizations without getting your app banned in Google Play.
You should also check whether battery optimizations are turned off in your receiver to prevent crashes via:
if (Build.VERSION.SDK_INT < 26 || getSystemService<PowerManager>()
?.isIgnoringBatteryOptimizations(packageName) != false) {
startService(Intent(context, MyService::class.java))
} // else calling startService will result in crash
if you have integrated firebase messaging push notification then,
Add new/update firebase messaging dependencies for android O (Android 8.0), due to Background Execution Limits.
compile 'com.google.firebase:firebase-messaging:11.4.0'
upgrade google play services and google repositories if needed.
Update:
compile 'com.google.firebase:firebase-messaging:11.4.2'
Use startForegroundService() instead of startService()
and don't forget to create startForeground(1,new Notification()); in your service within 5 seconds of starting service.
it's actually happening because the phone is on offscreen, or you pressed the power button while starting the service. solution for this which worked for me is to
start an activity and when it will go in onResume then start the service.
in my case, it was booting up and starting a service.
I am very dissatisfied with the answers here. What if foreground service nor WorkManager fit the use case?
I've come to a solution, where I use process scope and make sure to not include scope cancellation exception in the logging logic.
Like so:
with(ProcessLifecycleOwner.get()) {
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
try {
context.startService(context, Service::class.java)
} catch (ex: CancellationException) {
// app minimized, scope cancelled, do not log as error
} catch (ex: IllegalStateException) {
logToFirebase(ex)
}
}
}
}
More detailed in this article https://medium.com/#lepicekmichal/android-background-service-without-hiccup-501e4479110f
You may try this code to avoid crash. As google developers said in issue tracker.
private val activityManager by lazy { getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager }
//due to https://issuetracker.google.com/issues/113122354
private fun isInForegroundByImportance(): Boolean {
val importanceState = activityManager.runningAppProcesses.find {
it.pid == android.os.Process.myPid()
}?.importance ?: return false
return importanceState >= RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
and usage
override fun onResume() {
super.onResume()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || isInForegroundByImportance()) {
val intent = Intent(this, BluetoothScannerService::class.java)
this.startService(intent)
}
}
i had this problem too
added this library
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
and reinstalled the app solved this for me

Pass data to onDestroy() of Service

I want to know if the service was terminated from a particular activity, so I'm passing a string from that activity while calling stopServivce(service).
Here's the code :
Intent service = new Intent(Activity.this,
service.class);
service.putExtra("terminate", "activity terminated service");
stopService(service);
But I can seem to access this variable with getIntent().getExtras().getString("terminate); in the onDestroy() method.
[EDIT]
I found a way around this obstacle, but I'd like my question to still be answered. I just did whatever I had to do in the onDestroy() method in the activity and then called stopService(service). I was lucky that my situation didn't need anything more complicated.
There is no way of accessing the Intent in onDestroy. You have to signal the service some other way (Binder, Shared Preferences, Local Broadcast, global data, or Messenger). A nice example of using broadcast is given in this answer. You can also get this to work by calling startService instead of stopService. startService only starts a new services if one does not already exist, so multiple calls to startService is mechanism yo send Intents to the service. You see this trick is use by BroadcastReceivers. Since you have access to the Intent in onStartCommand, so you can implement termination by check the Intent extras and calling stopSelf if instructed to terminate. Here is a sketch of it in action --
public int onStartCommand(Intent intent, int flags, int startId) {
final String terminate = intent.getStringExtra("terminate");
if(terminate != null) {
// ... do shutdown stuff
stopSelf();
}
return START_STICKY;
}
Just to illustrate what iagreen suggests;
In Activity
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.package.yourfilter");
broadcastIntent.putExtra("activity_name", "your_activity");
sendBroadcast(broadcastIntent);
In Service
private YourActionReceiver abc;
this.abc = new YourActionReceiver();
registerReceiver(this.abc, new IntentFilter("com.package.yourfilter"));
public class YourActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Get the name of activity that sent this message
}
}
Global State
is your friend. :)
Check a Global String whenever you need to (say before terminating). You may also want to have an enumeration state. Or a flag to see if state is valid.
Recipe:
The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.
As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.
The way to do this is to create your own subclass of android.app.Application, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
#Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
class BlahBlah extends Service {
#Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).
Credits go to #Soonil

How do I cancel all pending intents that are qued for intent Service

I have an intentservice that gets qued by the user and by my app automatically. I need to be able to kill all pending intents that are qued when the user logs out of my application, but I cannot seem to get that to work. I have tried stopService() and stopself(), but the intents continue to fire off the intentservice after the user has logged out. I would try to get the id of the intent but that is difficult as everytime the intentservice starts, the variable holding the intent id's is empty. Here is my intentservice code:
public class MainUploadIntentService extends IntentService {
private final String TAG = "MAINUPLOADINTSER";
private GMLHandsetApplication app = null;
private SimpleDateFormat sdf = null;
public boolean recStops = true;
public MainUploadIntentService() {
super("Main Upload Intent Service");
GMLHandsetApplication.writeToLogs(TAG,
"GMLMainUploadIntentService Constructor");
}
#Override
protected void onHandleIntent(Intent intent) {
GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Started");
if (app == null) {
app = (GMLHandsetApplication) getApplication();
}
uploadData(app);
GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Finished");
}
#Override
public void onDestroy() {
GMLHandsetApplication.writeToLogs(TAG, "onDestroy Started");
app = null;
stopSelf();
GMLHandsetApplication.writeToLogs(TAG, "onDestroy completed");
}
public void uploadData(GMLHandsetApplication appl) {
//All of my code that needs to be ran
}
Unfortunately, I don't think it's possible to accomplish that with the standard IntentService methods since it doesn't offer a way to interrupt it while it's already going.
There are a few options I can think of that you can try to see if they fit your need.
Copy the IntentService code to make your own modifications to it that would allow you to remove pending messages. Looks like someone had some success with that here: Android: intentservice, how abort or skip a task in the handleintent queue
Instead of copying all the IntentService code, you might also be able to Bind to it like a normal Service (since IntentService extends Service) so you can write your own function to remove pending messages. This one is also mentioned in that link.
Rewrite the IntentService as a regular Service instead. With this option, you'd have more control over adding and removing messages.
I had what sounds like a similar situation where I was using an IntentService, and I eventually just converted it to a Service instead. That let me run the tasks concurrently and also cancel them when I needed to clear them.
Here
When should I free the native (Android NDK) handles? is the HangAroundIntentService class that has the method cancelQueue().
The class also has the method
public static Intent markedAsCancelIntent(Intent intent)
that converts an intent into a cancel intent, and
public static boolean isCancelIntent(Intent intent).
The class is based on the open-sourced Google's code.
Just a thought but inside of your onhandleintent can you have an argument that checks to see if app is running if not then don't run the code? example. In the start of your app you could have a static var
boolean appRunning;
Next in your onhandle of the intent, when you set the appRunning to false, after an onPause or onDestroy of activity, you could wrap the onhandleintent code in a boolean:
protected void onHandleIntent(final Intent intent) {
if(MainActivity.appRunning){
...
}
}
Just a thought

Service not getting started

I am writing my first service. My activity works well, but when I call my service, it doesn't.
It looks like it's onCreate() is not getting called.
My service code:
public class NeglectedService extends Service {
public static final String MY_SERVICE = "android.intent.action.MAIN";
public void onCreate() {
Toast.makeText(this, "Service onCreate...", Toast.LENGTH_LONG).show();
}
}
I am not even getting the Toast message.
Here is my activity
startService(new Intent(NeglectedService.MY_SERVICE));
My manifest
action android:name="android.intent.action.MAIN"
Did you enter something like
<service android:name=".subpackagename.ServiceName"/>
into your Android Manifest xml file?
Seeing as the NeglectedService.MY_SERVICE is just a string, in your startService call you're essentially calling:
startService(new Intent("android.intent.action.MAIN"));
Clearly that doesn't have any reference to your particular service and isn't what you want. Instead, either register the service for particular intent filters and include those in your intent, or call it by class:
startService(new Intent(this, NeglectedService.class));
Call your Service using an Explicit intent, instead of using an implicit action string, which should be more unique anyway. In other words, use this in your Activity code:
startService( new Intent(this, NeglectedService.class) );
Hope that helps!

Android: Obtaining a class after a call to startService()

I am getting confused with all the different terminology when using Android: Activity, Service...
Right now I create a service:
startService(new Intent(this, RingerServer.class));
And this service starts a thread:
public class RingerServer extends Service {
public void onCreate() {
super.onCreate();
new Thread(new Ringer()).start();
}
public class Ringer implements Runnable { ... }
public void refuseConnection() { ... }
}
In this service, the RingerServer, I also have methods that I want to use. I would like to keep a reference to the RingerServer. I would basically like the Activity that created the service to be able to call refuseConnection(), but not make that method static.
startService returns a ComponentName, so I've been trying to cast it back to RingerServer but that doesn't seem to work. I see that it has getClass() and I've checked and getClassName() gives me the correct class. I haven't been able to use getClass() properly though.
Is there any way I can please keep a reference to the newly created RingerServer class? I am sure this is trivial, but I am stuck right now.
Thank you very much,
James
You have two options
1.Override onStartCommand of the service and start the server with intent using an action. that intent will be received in service, based on the intent action you can call refuseConnection()
//In Activity
...
//Start the service
Intent intent=new Intent("com.xx.xx.REFUSE_CONNECTION");
startService(this,intent);
...
//In Service
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if(intent.getAction().equals("com.xx.xx.REFUSE_CONNECTION")){
//Refuse the connection
refuseConnection();
}else {
//Do something else
}
}
//In Manifest
<service android:name="RingerService">
<intent-filter>
<action android:name="com.xx.xx.REFUSE_CONNECTION"></action>
</intent-filter>
</service>
Implement AIDL interface and override onBind() of service , and use this interface to call refuseConnection(). Refer to this link http://developer.android.com/guide/developing/tools/aidl.html regarding AIDL.
You can use a ServiceConnection to get access to your service class. See sample code here:
Android service running after pressing Home key
That said, managing things via the service's onStart handler is much simpler.

Categories

Resources