Start a Service from an Activity - android

In my app, I have an Activity from which I want to start a Service. Can anybody help me?

Add this in your code
Intent serviceIntent = new Intent(this, ServiceName.class);
startService(serviceIntent);
Dont forget to add service tag in AndroidManifest.xml file
<service android:name="com.example.ServiceName"></service>
From the Android official documentation:
Caution: A service runs in the same process as the application in
which it is declared and in the main thread of that application, by
default. So, if your service performs intensive or blocking operations
while the user interacts with an activity from the same application,
the service will slow down activity performance. To avoid impacting
application performance, you should start a new thread inside the
service.

The application can start the service with the help of the Context.startService method. The method will call the onCreate method of the service if service is not already created; else onStart method will be called. Here is the code:
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.testApp.service.MY_SERVICE");
startService(serviceIntent);

First create service from android Manifest.xml file (i.e from application tab) and give some name to it.
On the activity on some event like click or touch to include the code from the service:
public void onClick(View v)
{
startService(new Intent(getApplicationContext(),Servicename.class));
}
If you want to stop the running or started service then include this code:
public void onclick(View v)
{
stopService(new Intent(getApplicationContext,Servicename.class));
}

The API Demos have some examples that launch services.

Use a Context.startService() method.
And read this.

in kotlin you can start service from activity as follow :
startService!!.setOnClickListener { startService() }
private fun startService(){
startService(Intent(this, HitroService::class.java))
}

If you want to start a service and it should run in background use START_STICKY in your corresponding service.
You can start service with on boot also,
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
And create receiver,
<receiver android:name=".auth.NotificationBroadcast" android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
In Brodcast Receiver add,
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("BroadcastReceiverBroadcast--------------------ReceiverBroadcastReceiverBroadcastReceiver----------------BroadcastReceiver");
if (intent != null) {
String action = intent.getAction();
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
System.out.println("Called on REBOOT");
// start a new service
startService(new Intent(getApplicationContext(),Servicename.class));
break;
default:
break;
}
}
}
And your service is like,

Related

Stopping a Service from Activity

I have problem with stopping a service from activity.
Declaration of my service:
public class MyService extends Service implements LocationListener { .. }
This service is called when the button is pressed:
public void startMyService(View view)
{
ComponentName comp = new ComponentName(getPackageName(), MyService.class.getName());
ComponentName service = startService(new Intent().setComponent(comp));
}
In another method (launched by button click) I want to stop it:
public void stopMyService(View view)
{
stopService(new Intent(this, MyService.class));
}
Unfortunately, it is not working. It seems to me that this service is replaced by another one. Furthermore, it´s cumulating - for example, when I start the service for the second time, there are two of them, running, etc. Could somebody help me? Thanks in advance for your help.
UPDATE : Android Manifest (only my service):
<service android:name=".MyService"
android:enabled="true"
android:exported="false"
android:label="LocationTrackingService"
/>
You could add a BroadcastReceiver to your service (or a static method - depending on your preferences) and call Context.stopService() or stopSelf(), e.g. add ...
public static String STOP_SERVICE = "com.company.SEND_STOP_SERVICE";
private final BroadcastReceiver stopReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(STOP_SERVICE)){
MyService.this.stopSelf();
}
}
};
... to your service (assuming it's called MyService). Then call registerReceiver(stopReceiver, STOP_SERVICE); in the onStartCommand() method and unregisterReceiver(stopReceiver); in onDestroy(). Finally send the broadcast from anywhere you need to stop the service:
Intent intent=new Intent();
intent.setAction(MyService.STOP_SERVICE);
sendBroadcast(intent);
If you have some threads you have to stop them before (probably you have and you started the service sticky, did you?)

Android remote Service start and stop

I'm developing an app that makes asynchronous calls to server for notifications. Everything works fine in the main activity. Now what's bothering me, that i need a service that would poll for notifications when the app is not active (just like GMail stock app). So I start remote service in another process in the main activities onStop function like that:
#Override
public void onStop() {
super.onStop();
if(prefs.getBoolean(OPTIONS_KEY_SERVICE, false)) {
startServiceIntent = new Intent(CloudAlarmsService.MY_SERVICE);
Bundle b = new Bundle();
b.putStringArray("duidCodes", duidCodes);
startServiceIntent.putExtras(b);
Log.d("SSE_SERVICE", "Starting Service");
startService(startServiceIntent);
}
}
It works fine, i get notifications after the activity was closed. Now i would like to stop remote service on activity start (so i won't have activity and service polling server concurrently). I do it like this:
#Override
public void onResume() {
super.onResume();
stopService(new Intent(CloudAlarmsService.MY_SERVICE));
Log.d("SSE_SERVICE", "Stopping service");
}
CloudAlarmsService.MY_SERVICE is a string in my service class:
public class CloudAlarmsService extends Service {
public static String MY_SERVICE = "cloudindustries.alarms.service.BACKGROUND_SERVICE";
...
and also it is declared in manifest xml like that:
<service android:process=":alarms_poller" android:name=".CloudAlarmsService">
<intent-filter android:label="#string/serviceStopService">
<action android:name="cloudindustries.alarms.service.BACKGROUND_SERVICE" />
</intent-filter>
</service>
But service is not stopped and it keeps working. After i close the main activity another instance of service spawns and continues polling.
Is there something i am missing out?
Or maybe this is a bad use for a remote service or even there is another type of service / manager which could be used for such purpose?
Thanks for any help!
Edit:
Question clarification: Is it possible to stop remote service from different activity (which did not start the service)?
try to stop CloudAlarmsService service as:
Intent intent = new Intent();
intent.setClass(getApplicationContext(), CloudAlarmsService.class);
getApplicationContext().stopService(intent);

Android kill process from broadcast receiver

Hi i'm looking to kill an activity in my application when the usb is disconnected i have a broadcast receiver and all set up and working fine
public class USBOff extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SdcardOff.class);
startActivity(intent1);
finish();
}
}
This code however tells me that the finish method and startActivity methods need to be created? why is this not working thank you for any help with my problem
startActivity is a Context method, not a BroadcastReceiver method. finish is an Activity method. Try this:
context.startActivity(intent1);
You can't call finish from a BroadcastReceiver.
I have found an interexting method :
Manfest :
android:launchMode="singleInstance"
<action android:name="com.gr.app.KILLSELF" />
receiver code :
Intent intentInterface = new Intent("com.gr.app.KILLSELF");
mContext.startActivity(intentInterface);
activity onCreate part :
if (intent.getAction().compareTo("com.gr.app.KILLSELF") == 0) {
finish();
};
It will not work in such configuration if you may have many instancesof activity (string android:launchMode="singleInstance" is a problem for you),
I hope it will help
Simple Logic :
If you dont want to kill the activity then do not use finish() And if you want to kill the activity then you should have to call finish();
So remove the finish(); from code and try it out.
Enjoy.

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!

Do I need to add an intent-filter when starting a service?

I am following a tutorial to setup a service to start on boot where the last piece of the code is:
Make an entry of this service in AndroidManifest.xml as
<service android:name="MyService">
<intent-filter>
<action
android:name="com.wissen.startatboot.MyService" />
</intent-filter>
</service>
Now start this service in the BroadcastReceiver MyStartupIntentReceiver’s onReceive method as
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.wissen.startatboot.MyService");
context.startService(serviceIntent);
}
As you see it uses intent-filters and when starts the service adds action.
Can I just use
startService(new Intent(this, MyService.class));
What's the advantage of one compared to the other?
Assuming this is all in one application, you can use the latter form (MyService.class).
What's the advantage of one compared to the other?
I'd use the custom action string if you wanted third parties to start this service.
As I have already mentioned in the comment, actions may be useful self-testing. E.g., a service performs a lot of tasks. For every task there is an action. If the service is started with an unknown action, an IllegalArgumentException will be thrown.
I usually use this approach in onStartCommand.
String action = intent.getAction();
if (action.equals(ACT_1)) {
// Do task #1
} else if (action.equals(ACT_2)) {
// Do task #2
} else {
throw IllegalArgumentException("Illegal action " + action);
}

Categories

Resources