Starting service from another service - android

I'm trying to start a service from another service. But wonder what's going wrong. The code is like
class Service1 extends GCMBaseIntentService {
#Override
protected void onMessage(Context arg0, Intent intent) {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
Intent service = new Intent(getApplicationContext(), Service2.class);
startService(service);
}
}
And Service2 is
class Service2 extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
}
}
I'm getting the Toast "Hello" in Service1 but not getting Toast "Service Started" from Service2

Instead of using getApplicationContext() you should use Service1.this or getBaseContext() . Have you declared your Service2 in the AndroidManifest?

Related

Passing data to service in oncreate()

I am passing the data from main activity to service.
I am getting these errors in Myservice.java
1. In override oncreate method - method does not override from superclass
2. The displayingText in run - cannot resolve symbol.
Mainactivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//load the layout file
}
String displayingText = "ABC";
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
startService(mIntent);//(new Intent(this, MyService.class));//use to start the services
mIntent.putExtra("PassToService",displayingText);
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
}
MyService.java
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)//if mTimer is activated
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
public int onStartCommand (Intent intent, int flags, int startId) {
String displayingText = intent.getStringExtra("PassToService");
Toast.makeText(getApplicationContext(), displayingText, Toast.LENGTH_SHORT);
return START_STICKY;
}
You have some problem in your code .
1.change the order of the code
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
// edited here
mIntent.putExtra("PassToService",displayingText);
startService(mIntent);
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
}
My code
String displayingText = "abc";
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
startService(mIntent);//(new Intent(this, MyService.class));//use to start the services
mIntent.putExtra("PassToService",displayingText);
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
}
2.register in your manifest for your service
<service android:name=".your_package.MyService"/>
Registered as
<service
android:name=".MyService"
android:enabled="true" />
But the value return nothing.
for StartService(View v)....
you still haven't implemented any action or event in onCreate method.
if you still have can't resove problem, use "Mainactivity.this" in place of this in StartService method.
You can pass data to service like below :-
Intent intent = new Intent(MainActivity.this , GPSTracker.class);
intent.putExtra(YOURKEY , VALUE);
startService(intent);
and you can get your data on onStartCommand() method :-
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
intent.getStringExtra(YOURKEY)
}
return START_STICKY;
}
I had done as below. But the toast message return no character(no value)
public int onStartCommand (Intent intent, int flags, int startId) {
String displayingText = intent.getStringExtra("PassToService");
Toast.makeText(this, displayingText, Toast.LENGTH_SHORT).show();
return START_STICKY;
}
You need to use onStartCommand to get the data/values from the activity to service.,
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
after this you can override the oncreate method and display the stuffs.
But you need to remember that ALWAYS ONCREATE METHOD WILL BE EXECUTED WHEN WE USE startservice method in our activity
In Your Activity, just use the below code:
private void initializeService(String Index) {
Intent intent = new Intent(Detail_Test_run.this, Servicelay.class);
intent.putExtra("Index",Index);
startService(intent);
finish();
}
Then in your service use:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
index= intent.getStringExtra("Index");
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
addView(index);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
For me it worked well, where I started calling all my functionalities from onStartCommand() instead of onCreate()
I think you should use sharedpreferances as data wont be available for service in background.
So in your startService() method:
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
startService(mIntent);
SharedPreferences sp=getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putString("data",displayingText).commit();
editor.apply();}
And in your service class's onStartCommand() add these lines
SharedPreferences prefs = getSharedPreferences("MyPrefs",MODE_PRIVATE);
String string = prefs.getString("data","");
Hope this helps :)

Keep service while phone is alive

I have broadcast receiver that activates on phone boot
public class autostart extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {
Intent intent = new Intent(arg0, MyService.class);
arg0.startService(intent);
Log.i("Autostart", "started");
}
}
The service is very simple it just keeps registered an broadcast receiver that can be only registered by code and not from manifest
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
ScreenOffReceiver actionScreenOffReceiver;
#Override
public void onStart(Intent intent, int startid)
{
try {
IntentFilter intentfilter = new IntentFilter();
intentfilter.addAction(Intent.MY_ACTION);
registerReceiver(actionScreenOffReceiver = new ScreenOffReceiver(),
intentfilter);
} catch (Exception e) {
}
}
}
The problem is that if the app get closed, for example with call of finish() on some activity, then the service just dies.
How can I keep the service running till the phone is turned on
what is the right way to do this ?
You don't need an BroadcastReceiver just add this code in your Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
Source: Service | Android Developers

Keep alive Service in background?

For a demo I print a Toast after Evert 10 sec. using Service class.
It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.
But I want to that toast either I'll kill the App or back press Here is code snippet :
ServiceDemo.java
public class ServiceDemo extends Activity {
private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {
#Override
public void run() {
as();
myHandler.postDelayed(this, 10000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
myHandler.postDelayed(drawRunnable, 10000);
startService(new Intent(this, MyService.class));
}
public void as(){
startService(new Intent(this, MyService.class));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Service.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}
Edit 1
moveTaskToBack(true);
I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, Service not responding
I think you need to override onStartCommand instead of onStart()
like:
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
i think AlarmManager is what you want.
You have to user AlarmManager, here's an example : Alarm Manager Example
Your task will be executed even if the application is terminated.
But if the application is killed by the user, the Alarm will be canceled. See this discussion How to create a persistent AlarmManager

Send data from Activity to Service

How can I send data from the current Activity to a background Service class which is running at certain time? I tried to set into Intent.putExtras() but I am not getting it in Service class
Code in Activity class which calls the Service.
Intent mServiceIntent = new Intent(this, SchedulerEventService.class);
mServiceIntent.putExtra("test", "Daily");
startService(mServiceIntent);
Code in Service class. I treid to put in onBind() and onStartCommand(). None of these methods prints the value.
#Override
public IBinder onBind(Intent intent) {
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
//String data = intent.getDataString();
Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();
Log.d(APP_TAG,intent.getExtras().getString("test"));
return null;
}
Your code should be onStartCommand. If you never call bindService on your activity onBind will not be called, and use getStringExtra() instead of getExtras()
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();
Log.d(APP_TAG,intent.getStringExtra("test"));
return START_STICKY; // or whatever your flag
}
If you want to pass primitive data types that can be put into Intent I would recommend to use IntentService. To start the IntentService, type in your activity:
startService(new Intent(this, YourService.class).putExtra("test", "Hello work");
Then create a service class that extends IntentService class:
public class YourService extends IntentService {
String stringPassedToThisService;
public YourService() {
super("Test the service");
}
#Override
protected void onHandleIntent(Intent intent) {
stringPassedToThisService = intent.getStringExtra("test");
if (stringPassedToThisService != null) {
Log.d("String passed from activity", stringPassedToThisService);
// DO SOMETHING WITH THE STRING PASSED
}
}

Calling an Activity from a Service

I have a service class for an alarm service containing the service methods. These methods are called when the alarm service is activated. What I want to do is to call an intent to another class in one of these methods that are called in the service class (when the alarm goes off). All it does is just flag up errors when calling the intent. This only happens in the methods that are called when the alarm service is activated (methods in service class). Is this because the class extends Service and not extends Activity? I'm not sure, any ides?
(Below is my service class, when the intent to another activity is called in the onStart method the app force closes.)
public class MyAlarmService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
//////////////////////////////////////////////////////////////////////////////////
Intent i = new Intent("com.exercise.AndroidAlarmService.HELLO");
startActivity(i);
The intent that is send to open another class, an activity.
**
/////////////////////////////////////////////////////////////////////////////////
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
One of these errors on the LogCat is:
06-24 01:11:36.857: E/AndroidRuntime(10805): java.lang.RuntimeException: Unable to start service com.exercise.AndroidAlarmService.MyAlarmService#412f23f8 with Intent { flg=0x4 cmp=com.exercise.AndroidAlarmService/.MyAlarmService (has extras) }: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
Have you tried what the error log suggests?
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
You can call an Activity using onStart() of your service.....
#Override
public void onStart(Intent intent, int startId) {
...
Log.i("Service", "onStart() is called");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setClass(<Set your package name and class name here>);
startActivity(callIntent);
...
}
You can do it by enabling the flag as suggested by others. The reason why it is prevented by default is because services are prone to automatic restart by system, in the background. If you are starting an activity during onStart of a service, this activity starts irrespective of what the user may be doing. This will be bad user experience. Please bear this caveat in mind and have work around for this scenario.

Categories

Resources