Service not getting started - android

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!

Related

How to execute methods from a running service from broadcast?

on a broadcast I want to call a non static method from Service XYZ. The Service is start by the receiver on boot.
Has someone a idea to run methods from this running service?
One solution in this forum is to make the method static and use a singleton pattern to execute. But is there another method? Maybe with a binder?
//EDIT for example i have the following clases:
public class MyService extends Service{
.....
public void method(){
//TODO
}
}
public class MyBroadcastReceiver extends BroadcastReceiver{
.....
public void onReceive(Context context, Intent intent) {
String intentAction=intent.getAction();
if(intentAction.equals(Intent.ACTION_BOOT_COMPLETED)){
//start service
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
else{
//TODO call method() in MyService
}
}
how can i call the method method()? I know that i can cast with context.getSystemService() system services. But how can i get my own service object?
greetings
You can add an action string to your intent using setAction in the intent that launches the Service. In your service's onStartcommand you can extract the intent's action, and based off that you can execute the method in your service.
You will always send commands to your service using startService this will not launch your service twice. It will either get started once, or the new intent is sent to the service.
So, in your on boot completed section you should set the intent action to whatever you want, and start the service - you can remove the else block completely.
In your Service implement the onStartCommand, extract the intent's action, and based off that action you can just execute your method.

unable to start service from activity using startService

all tutorials tell me to do this:
startService(new Intent(this, MyService.class));
but there is no constructor that takes Activity, Class and so i get syntax errors
http://developer.android.com/reference/android/content/Intent.html
I am attempting to spawn a service this way,
startService(new Intent(getApplicationContext(), MyService.class));
but my service never executes.
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
//do stuff
}
}
how can i spawn a service?
ANSWER: my android manifest didnt specifcy package
Actual problem (as found in comments) added here :
The service was in a different package, so in the manifest it has to be fully qualified, e.g. <service android:name="actual.package.of.MyService"/>
Old Answer:
If you try to launch the service in an inner class, you should not write:
startService(new Intent(this, MyService.class));
But:
startService(new Intent(ActivityName.this, MyService.class));
Make sure your service appears in the manifest.
Add a debug print inside the onHandleIntent to see whether it starts or not.
Services are not something visible
Possibly you have not declared the service in manifest file.
I dont think there is any problem with the code.
Override onstartCommand and oncreate method and just put a log statement and check logcat

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.

Android Communication between Broadcast Receiver and MainActivity (Send data to activity)

I've a simple Main Activity which has to stop till an SMS is received... How can I launch a method from the MainActivity within the BroadcastReceiver's onReceive() Method?
Is there away with Signal and Wait? Can I pass something with a pending Intent, or how can I implement this communication?
Communication from BroadcastReceiver to Activity is touchy; what if the activity is already gone?
If I were you I'd set up a new BroadcastReceiver inside the Activity, which would receive a CLOSE message:
private BroadcastReceiver closeReceiver;
// ...
closeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//EDIT: receiving parameters
String value = getIntent().getStringExtra("name");
//... do something with value
finish();
}
};
registerReceiver(closeReceiver, new IntentFilter(CLOSE_ACTION));
Then from the SMS BroadcastReceiver you can send out this action:
Intent i = new Intent(CLOSE_ACTION);
i.putExtra("name", "value"); //EDIT: this passes a parameter to the receiver
context.sendBroadcast(i);
I hope this helps?
I had the exact same problem, I tried using intent but i was unsuccessful
The easiest way to use it would be using static methods and static variables
MainActivity.java
public static void stopsms()
{
/*
some code to stop the activity
*/
}
SMSReceiver.java
at the end call this function
MainActivity.stopsms();
It works amazing if your code does not affect when you use static methods and variables. Let me know if you need any help.
The problem with registering a second receiver within the activity, however, is that it will not be persistent like registering in the manifest... thus, although, this solution may work, will only work if the activity is running in background.
it's easy, use interface like that:
1) in your broadcast receiver create an interface.
public interface ChangeListener{
public void functionWhoSendData(String type);
public void etc();
}
and instantiate that interface in your broadcast receiver, use it:
public void onReceive(....
String data=functionWhereYouReceiveYouData();
ChangeListener.functionWhoSendData(data);
}
And in your activity, make it implements your interface

Start a Service from an Activity

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,

Categories

Resources