Android Service Activity Intent - android

I want to pass a string from activiy to service.
Bundle mBundle = new Bundle();
mBundle.putString("MyString", string);
mIntent.putExtras(mBundle);
startService(mIntent);
this is in Activity class
Intent myIntent = getIntent();
String value = myIntent.getExtras().getString(key);
and this is in Service class
It doesn't accept getIntent() method :S I don't know what I'll do

The code in the service must be placed in onStart(Intent intent, int startid) method and the code becomes String value = intent.getExtras().getString(key);

When you start the service using startService(mIntent) the service's onStartCommand is called which is good place to handle the intent.

Move the part of your code that depends on the intent to onStartCommand: http://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)
OnStartCommand was called OnStart before api version 5, follow link to documentation for further information about backwards compatibility in your app.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String value = intent.getExtras().getString(key);
}
Also remember to move heavy code into a background thread that you start in onStartCommand, as otherwise you will run into an Application Not Responding error.

Related

How to update value in Service from activity

I have a service start in Activity A with
private void startService() {
Intent pushIntent = new Intent(this, MyService.class);
pushIntent.putExtra(MyService.TYPE_SCREEN, 1);
startService(pushIntent);
}
in my Service I get data from onStartCommand
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
typeScreen = intent.getExtras().getInt(TYPE_SCREEN);
return Service.START_STICKY;
}
I want when change from activity A to activity B, I will update type of screen from 1 to 2 in Service.
How I can do it?
Android only create one instance of a service.
Request that a given application service be started. The Intent can
either contain the complete class name of a specific service
implementation to start, or an abstract definition through the action
and other fields of the kind of service to start. If this service is
not already running, it will be instantiated and started (creating a
process for it if needed); if it is running then it remains running.
So in your case, the service is already running, then you just have to send the intent with the screen 2 extra. It will only call the onStartCommand Override method.
Intent pushIntent = new Intent(this, MyService.class);
pushIntent.putExtra(MyService.TYPE_SCREEN, 2);
startService(pushIntent);

Why Android app crash when close app if I getExtras in Service?

In Activity I start a service
Intent serv=new Intent(this, MyService.class);
serv.putExtra("mac", "mac");
startService(serv);
In the service, I get the parameter
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String mac=intent.getExtras().getString("mac");
return super.onStartCommand(intent, flags, startId);
}
Then I kill the app, the app will crash, and the service will also crash.
If I remove this line, then it will be no problem, the service also alive after I killed the app.
String mac=intent.getExtras().getString("mac");
Why the app crash?
super.onStartCommand(intent, flags, startId) returns the START_STICKY flag by default which, according to the docs, mean that:
"if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent."
Since the Intent isn't being redelivered you likely get NPE when calling intent.getExtras().
To redeliver the Intent return the START_REDELIVER_INTENT flag from onStartCommand():
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
return START_REDELIVER_INTENT;
}
You are putting extras to wrong intent bleService.putExtra("mac", "mac");
Instead you should write serv.putExtra("mac", "mac");
Also you should always check if there are extras
if(getIntent().hasExtra("mac"){
//do some stuff
}

eliminate the value of a variable in a service in android

my program is an activity to identify a user when that user is identified by pressing a button sends the string to another class (alarmChecker) that extends to a service. This service does is check every 30 seconds if the value of a database has changed, and if you notice changes launches.
Sending the String in the main class (MainActivity) I do it like this:
/ / Class MainActivity
Intent intent = new Intent (MainActivity.this, alarmChecker.class);
Bundle data = new Bundle ();
data.putString ("user", user);
intent.putExtras (data);
pendingIntent = PendingIntent.getService (MainActivity.this, 0, intent, 0);
Then the class "alarmChecker" receives the parameter as follows:
/ / class alarmChecker
#Override
public int onStartCommand(Intent intent, int flags, int startId){
super.onStartCommand(intent, flags, startId);
// Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
Bundle data = intent.getExtras();
user = data.getString("user");
Toast.makeText(getApplicationContext(), "user: "+user, Toast.LENGTH_LONG).show();
}
and I want to do is if the user presses the Return button or exit the application and return to the main screen (MainActivity) and identifies with another different user, alarmChecker class take the new values​​, but the problem is that the grabs. Always have the values ​​you enter the first time.
How to solve it?
Thanks for answering and greeting.
For your immediate question, your service can be updated with new values if you implement onStartCommand() in your service - it gets called every time the service receives a start intent, regardless of whether or not it has already started..
Unrelated to the question, in the long term, you might consider rethinking your design, as watching the database is a solved problem for you through the ContentObserver API, which does this kind of event from database it sounds like you're looking for.

IntentService STICKY destroyed but service keeps logging data in Android 2.3.4

I have an Android application.
In one activity I start a service like this:
Intent startIntent = new Intent(_context, HandlingService.class);
_context.startService(startIntent);
HandlingService is defined as follows:
public class HandlingService extends IntentService
Then inside HandlingService I have this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
Log.v(ApplicationName,"HandlingService.onStartCommand");
if ((flags & START_FLAG_RETRY) == 0){
Log.v(ApplicationName,"Service is restarting");
}
return START_STICKY;
}
and this:
#Override
protected void onHandleIntent(Intent sourceIntent) {
Log.v(ApplicationName, "HandlingService.onHandleIntent");
sendSomething();
}
and lastly:
protected void sendSomething() {
while (numberOfTry > 0) {
numberOfTry++;
Log.v(ApplicationName,"HandlingService.sending Something. Try# " + numberOfTry);
}
}
numberOfTry starts in 1.
Then from the activity that starts the service, when I click on a cancel button I call this:
Intent stopIntent = new Intent(CallingActivity.this, HandlingService.class);
CallingActivity.this.stopService(stopIntent);
I see HandlingService.OnDestroy being called, but I keep seeing the log with "HandlingService.sending Something. Try# " and the increasing numbers.
Question: Why it keeps alive if I already stopped it with the call to stopService?
Thanks in advance! Guillermo.
The documentation for IntentService explicitly states that you should not override onStartCommand() in your derived class. You are probably messing up the internal mechanics of the IntentService.
Either derive your class directly from Service or use the framework that IntentService already gives you (for starting/stopping itself).
from IntentService javadoc
public void setIntentRedelivery (boolean enabled)
Sets intent redelivery preferences. Usually called from the constructor with your preferred semantics.
If enabled is true, onStartCommand(Intent, int, int) will return START_REDELIVER_INTENT, so if this process dies before onHandleIntent(Intent) returns, the process will be restarted and the intent redelivered. If multiple Intents have been sent, only the most recent one is guaranteed to be redelivered.
If enabled is false (the default), onStartCommand(Intent, int, int) will return START_NOT_STICKY, and if the process dies, the Intent dies along with it.

Pass String from activity to service?

I am familiar with the method of passing arrays from one activity to another activity using putExtra and getExtra methods. However, whenever I try to get it from a service the following code doesn't work:
Bundle b = this.getIntent().getExtras();
String Array = b.getStringArray("paths");
It is not recognizing the following:
this.getIntent().getExtras();
Any ideas?
EDIT
in the activity class I have the following:
toService = new Intent();
toService.setClass(this, Service.class);
toService.putExtra("paths",Array);
in the service class:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
if(extras!=null)
{
Paths = extras.getStringArray("paths");
Toast.makeText(protectionService.this, Paths[0], Toast.LENGTH_SHORT).show();
}
return 0;
}
Nothing is appearing since Paths is not being assigned apparently.
Paths = extras.getStringArray("paths");
Doesn't seem to work.
Where are you trying to access getIntent?
Here is a snippet from a program I have written which uses the getExtras:
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Bundle extras = intent.getExtras();
if (extras != null) {
// Do what you want
}
}
However, onStart is now deprecated so you should really use onStartCommand.
You get the intent as one of the parameters.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Otherwise you could use AIDL, Preferences or any other example answered here: How to access a variable present in a service
Same question has already been answered Android: how to get the intent received by a service?
Edit:
If you use this
toService = new Intent();
toService.setClass(this, Service.class);
toService.putExtra("array",Array);
You need to get the extras with the same key, here the key is "array"
Paths = extras.getStringArray("array");

Categories

Resources