NullPointerException while retrieving Extras from Intent - android

I'm working on building a Location_Service for my Android App.I have a Service say , T_Service that starts on phone boot and checks for few conditions in its onStartCommand() to start my Location_Service. I want to send these conditions as an intent from a broadcast receiver associated to with the T_Service.
I do the following:
In the Broadcast Receiver
public class T_BroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,T_Service.class);
i.putExtra("PARENT_ACTIVITY_NAME","com.example.helloworld");
context.startService(i);
}
}
In the T_Service class:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
}
I get a NullPointerException when my code reaches the above point that tries to print the value associated with the key that was set in the Intent.
Kindly advise me on how to go about the case of adding extras to an intent of a Service like T_Service that starts on phone boot.
The Stack trace for the Exception :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service org.abc.def.services.TService#41593b58 with null: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2387)
at android.app.ActivityThread.access$1900(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.abc.def.services.TrackerService.onStartCommand(TrackerService.java:140)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2370)
            at android.app.ActivityThread.access$1900(ActivityThread.java:127)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4511)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
            at dalvik.system.NativeStart.main(Native Method)

From the documentation (onStartCommand):
Parameter "intent": The Intent supplied to startService(Intent), as given.
This may be null if the service is being restarted after its process has gone
away, and it had previously returned anything except
START_STICKY_COMPATIBILITY.
If you're running this on phone boot is likely that you will get null on the intent because the process that started it has gone away.
To receive the the same intent you would need to return START_REDELIVER_INTENT in the onStartCommand method, as follows:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
return Service.START_REDELIVER_INTENT;
}
Returning START_REDELIVER_INTENT will make the intent parameter to be passed again to the onStartCommand method whenever the service get restarted (e.g on phone boot).
For more details check the documentation.
START_REDELIVER_INTENT
Constant to return from onStartCommand(Intent, int, int): if this
service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int)), then it will be scheduled for a
restart and the last delivered Intent re-delivered to it again via
onStartCommand(Intent, int, int)

Please read the javadoc for onStartService. It says that the intent parameter can be null, so you should always check it for null before calling methods on it.
My experience is that even when you think that an IntentSevice will never receive a null there, it is actually still possible in extremely rare circumstances. So you should still check it for null even if you don't think it will happen.

replace this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
}
with this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Bundle b = getIntent().getExtras();
if (b != null){
Log.d("APP","The intent has parent activity :"+b.getString("PARENT_ACTIVITY_NAME")); }

Per the Intent API documentation, you must include a package name in the extra's name.
public Intent putExtra (String name, String value)
Added in API level 1
Add extended data to the intent. The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
Parameters
name The name of the extra data, with package prefix.
value The String data value.
Returns
Returns the same Intent object, for chaining multiple calls into a single statement.
See Also
putExtras(Intent)
removeExtra(String)
getStringExtra(String)

Please check your intent and extra string before accessing. May be it is null
if(intent.getExtras()!=null && intent.hasExtra("PARENT_ACTIVITY_NAME")){
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
}
To pass an intent, please refer older thread.
Pass data from Activity to Service using an Intent

Related

Stop a service after MainActivity is closed (EDITED)

I think im not clear at all, i do want the service to persist even if the main activity is destroyed via user action or android system does it, it does it well, but when the app is reopened at certain point i will want to check if a bg activity exists and stop it using a action button, THX in advance.
I launch a background service, in my MainActivity I can stop it and rerun it, the service persists when the app is closed from the running apps list, the problem is when I relaunch the closed app an try to stop the service with a button I have the app crashes cause it obviously tries to stop a service from which it no longer has a reference.
private void startBg(){
if (!hasPermissions() || mScanning) {
return;
}
clearLogs();
BgServiceIntent = new Intent(MainActivity.this, BgScanService.class);
startService(BgServiceIntent);
}
private void stopBg(){
stopService(BgServiceIntent);
}
Calling stopBg() after reopening the app fails, because BgServiceIntent no longer points to this service and thus I get this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: mobile.link.imbera.apsys.imberalink, PID: 20104
java.lang.NullPointerException
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1568)
at android.app.ContextImpl.stopServiceCommon(ContextImpl.java:1628)
at android.app.ContextImpl.stopService(ContextImpl.java:1589)
at android.content.ContextWrapper.stopService(ContextWrapper.java:499)
at mobile.link.imbera.apsys.imberalink.MainActivity.stopBg(MainActivity.java:180)
at mobile.link.imbera.apsys.imberalink.MainActivity.lambda$onCreate$1$MainActivity(MainActivity.java:124)
at mobile.link.imbera.apsys.imberalink.MainActivity$$Lambda$1.onClick(Unknown Source)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
If the service already running in background then you need to call stopSelf() on same instance of that service .
Now as per service life Cycle onCreate() only call once in the lifetime of service .
WhereAs onStartCommand get called each time you call startService() with new intent. So what you can do is to pass a flag in intent to stop it .
Intent BgServiceIntent = new Intent(MainActivity.this, BgScanService.class);
BgServiceIntent.putExtra("close",true);
startService(BgServiceIntent);
And in Service .
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean shouldClose=intent.getBooleanExtra("close",false);
if(shouldClose){
stopSelf();
} else {
// Continue to action here
}
return START_STICKY;
}
Maybe all you need to do is check to see if it's null before attempting to stop it:
private void stopBg(){
if(BgServiceIntent != null)
stopService(BgServiceIntent);
}
First of all start a service in START_NOT_STICKY.
Override this method in your Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
and add this in your MainActivity.class
#override
private onDestroy() {
stopService(YourActiveService);
finishAffinity();
super.onDestroy()
}

NPE in android service onStartCommand while using START_REDELIVER_INTENT

I'm using the following code in my service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mStartId = startId;
handleStartCommandIntent(intent);
return START_REDELIVER_INTENT;
}
private void handleStartCommandIntent(#Nullable Intent intent) {
if (mCompositeDisposable == null) {
mCompositeDisposable = new CompositeDisposable();
}
checkNotNull(intent, "intent cannot be null");
String type = intent.getStringExtra(SERVICE_REQUEST_TYPE);
<...>
}
#Override
public void completed() {
stopSelf(mStartId);
}
checkNotNull is the first point where intent is looked at, however I'm not seeing my custom message in the stack trace. The check method looks as following:
public static <T> T checkNotNull(T reference, #Nullable Object errorMessage) {
if(reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
} else {
return reference;
}
}
However, I'm still seeing an NPE in my Crashlytics logs:
Fatal Exception: java.lang.RuntimeException: Unable to start service com.myapp.app.internal.service.MessagingService#4134a7b8 with Intent { cmp=com.myapp.app/com.myapp.app.internal.service.MessagingService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2608)
at android.app.ActivityThread.access$1900(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4847)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:535)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by java.lang.NullPointerException
at com.myapp.app.internal.service.MessagingService.onStartCommand(MessagingService.java:1065)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2591)
at android.app.ActivityThread.access$1900(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4847)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:535)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(NativeStart.java)
According to the docs my service should never receive a call with a null intent:
Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).
I couldn't reproduce it on my device, but I can see multiple users crashing with the same error.
Any suggestions why this might be happening and how to fix it?

Android service with START_STICKY crashes on killing app

This is my Service getting called on button click from an Activity. If I swipe my Activity left while Service is running it crashes. I have also tried running it in separate process by putting in android:process=":remote" in the manifest but it is still the same.
#Override
public void onCreate(){
super.onCreate();
Log.d("Service", "Creating");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Log.d("Started", "Service");
type = intent.getIntExtra("Type",-1);
mode = intent.getIntExtra("Mode",-1);
rank = intent.getIntExtra("Rank", -1);
latitude = intent.getDoubleExtra("Lat", -1.0);
longitude = intent.getDoubleExtra("Long", -1.0);
startTime = intent.getLongExtra("Start", 0);
endTime = intent.getLongExtra("End", 0);
The error I am getting is:
java.lang.RuntimeException: Unable to start service com.routofy.routofytest.MyLocationService#374afe93 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2913)
at android.app.ActivityThread.access$2100(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at com.routofy.routofytest.MyLocationService.onStartCommand(MyLocationService.java:89)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2896)
at android.app.ActivityThread.access$2100(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
That is null pointer on type = intent.getIntExtra("Type",-1);
I understand that killing the app is killing the process and Intent this Service is getting is coming out to be null. But how to handle such cases that even if Activity is killed Intent is handed over to Service?
I want service to be totally independent of Activity. Also I am running it like:
Intent pickIntent = new Intent(getApplicationContext(),MyLocationService.class);
I understand that killing the app is killing the process and intent this service is getting is coming out to be null.
Since you haven't posted the return value of onStartCommand() I believe that it's START_STICKY meaning that the service is recreated by the system with null Intent passed in.
But how to handle such cases that even if activity is killed intent is handed over to service.
Just return START_REDELIVER_INTENT flag, which means that:
"If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to the service."

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.

Android Service Activity Intent

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.

Categories

Resources