Unable to start service [service name] with null - android

i recently coded a Android Widget and tested it on Emulator as well as my Galaxy S , it worked fine on both, after i posted the same to android market now i am getting some error reports.
i am stating a service in the onUpdate of Widget Class like this:
if (appWidgetIds != null) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to
// this
// provider
for (int i = 0; i < N; i++) {
// Start Service for each instance
int appWidgetId = appWidgetIds[i];
Intent active = new Intent(context, DialerService.class);
active.setAction("Start");
active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetId);
context.startService(active);
}
}
the error which some people are getting is:
java.lang.RuntimeException: Unable to start service dialer.impact.DialerService#45f926f0 with null: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3282)
at android.app.ActivityThread.access$3600(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2211)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
**at dialer.impact.DialerService.onStart(DialerService.java:18)**
at android.app.Service.onStartCommand(Service.java:420)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3267)
... 10 more
error states a NullPointerException on line 18 of the ServiceClass which is this:
#Override
public void onStart(Intent intent, int startId) {
//Line 18th
String command = intent.getAction();
int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID);
RemoteViews remoteView = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.main);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(getApplicationContext());
}
Line 18 is the String command = intent.getAction();
what could be the reason for intent being null
please help

According to the documentation for onStart() (actually onStartCommand() but the parameters are the same):
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.

Hi just to add on to this, so the workaround is just to add a if(intent!=null) before the getAction()? If I do this, will the service start up properly later on it's own? Meaning the OS actually helps me start the service properly in the case of a null intent. I'm afraid of ending up in a situation where the service doesn't get started at all.

Related

Launch application after PackageInstaller finished (self) updating

After the PackageInstaller successfully (self) updates the application, the application closes and doesn't launch again.
Possible duplicate: Android PackageInstaller, re-open the app after it updates itself
The situation is pretty similar, ill show some code snippets first.
AndroidManifest.xml
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
My PackageInstaller session runs in an AsyncTask:
PackageInstaller packageInstaller = ctx.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams parameters = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
parameters.setAppPackageName(StaticData.TerminalPackageName);
progressChanged(10);
try {
int sessionId = packageInstaller.createSession(parameters);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
ProgressApproximatorHandler progress = startProgressApproximator(10, 100, 5);
OutputStream installerStream = session.openWrite("INSTALL_TERMINAL", 0, mApplicationLength);
installerStream.write(firmwareData, 0, mApplicationLength);
// This call ensures every byte on the stream is committed to disk.
session.fsync(installerStream);
installerStream.close();
Intent intent = new Intent(ctx, UpdateReceiver.class);
intent.setAction(Intents.APK_INSTALL_FINISHED_INTENT);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
mContext.get(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Sealing the session.
session.commit(pendingIntent.getIntentSender());
session.close();
progress.stop();
} catch (IOException e) {
Logger.error(mLogTag, e, "Failed to create an installer session.");
return false;
}
At the end of this snippet, you can see the setup of an Intent to send. I've tried many variations and none of them worked. For example:
Intent intent = new Intent(Intents.APK_INSTALL_FINISHED_INTENT);
and
Intent intent = new Intent("android.intent.action.MY_PACKAGE_REPLACED");
My receiver never receives the intent.
public class UpdateReceiver extends BroadcastReceiver {
private static final String TAG = "UPDATE";
#Override
public void onReceive(Context context, Intent intent) {
Logger.info(TAG, "Intent action: " + intent.getAction());
Logger.info(TAG, "updated");
}
}
EDIT: Somehow I managed to restart the app autimatically but it gets killed after a 1-3 seconds. I found the following error in the logcat of the system.
W/ActivityManager: Unable to send startActivity intent
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MY_PACKAGE_REPLACED from pid=-1, uid=10071
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:18195)
at com.android.server.am.ActivityManagerService.broadcastIntentInPackage(ActivityManagerService.java:18777)
at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:308)
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205)
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7409)
at android.content.IntentSender.sendIntent(IntentSender.java:190)
at android.content.IntentSender.sendIntent(IntentSender.java:154)
at com.android.server.pm.PackageInstallerService$PackageInstallObserverAdapter.onPackageInstalled(PackageInstallerService.java:1069)
at android.app.PackageInstallObserver$1.onPackageInstalled(PackageInstallObserver.java:34)
at com.android.server.pm.PackageInstallerSession.dispatchSessionFinished(PackageInstallerSession.java:1137)
at com.android.server.pm.PackageInstallerSession.-wrap2(PackageInstallerSession.java)
at com.android.server.pm.PackageInstallerSession$4.onPackageInstalled(PackageInstallerSession.java:648)
at com.android.server.pm.PackageManagerService.handlePackagePostInstall(PackageManagerService.java:1809)
at com.android.server.pm.PackageManagerService.-wrap25(PackageManagerService.java)
at com.android.server.pm.PackageManagerService$PackageHandler.doHandleMessage(PackageManagerService.java:1438)
at com.android.server.pm.PackageManagerService$PackageHandler.handleMessage(PackageManagerService.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
I am not sure if this is the reason for it.
EDIT2: Now I receive the intent, thus the app is running. The problem now is that its in the back stack.
I have a launcher app that could re-launch the main (updated) app but that doesn't sound clean code to me.
EDIT3:
I tried David's answer but I receive the following error:
E/ActivityManager: Failure starting process com.example.myapp
java.lang.SecurityException: Package com.example.myapp is currently frozen!
at com.android.server.pm.PackageManagerService.checkPackageStartable(PackageManagerService.java:3197)
at com.android.server.am.ActivityManagerService.startProcessLocked(ActivityManagerService.java:3789)
at com.android.server.am.ActivityManagerService.startProcessLocked(ActivityManagerService.java:3749)
at com.android.server.am.ActivityManagerService.startProcessLocked(ActivityManagerService.java:3630)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:1255)
at com.android.server.am.BroadcastQueue$BroadcastHandler.handleMessage(BroadcastQueue.java:172)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
Note this is thrown by the android system, and not by my app.
The MY_PACKAGE_REPLACED Intent is broadcast by Android after your app is updated.
To restart your app after the update, you could pass a launch Intent to the PackageInstaller, like this:
Intent intent = getPackageManager().getLaunchIntentForPackage("my.package.name");
PendingIntent pendingIntent = PendingIntent.getActivity(
mContext.get(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
session.commit(pendingIntent.getIntentSender());
This should cause your app to be restarted after the update is completed.
While David Wasser's answer was probably the right one. I am closing my case because I'm having very strange and undefined behaviour, and I am pretty sure that's because I am using a custom ROM

NullPointerException while retrieving Extras from Intent

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

ReceiverCallNotAllowedException in BroadcastReceiver using application context

I am getting the following error on Android versions 4.1.2:
Fatal Exception: java.lang.RuntimeException: Unable to start receiver com.example.PluggedInBroadcastReceiver:
android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2287)
at android.app.ActivityThread.access$1600(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4961)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents
at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:152)
at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:146)
at com.example.PluggedInBroadcastReceiver.getBatteryLevel(Unknown Source)
at com.example.PluggedInBroadcastReceiver.onReceive(Unknown Source)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2280)
at android.app.ActivityThread.access$1600(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4961)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(NativeStart.java)
Here is the code that is causing the error. This receiver is being registered statically (in the AndroidManifest.xml) rather than dynamically:
public class PluggedInBroadcastReceiver extends WakefulBroadcastReceiver {
public static final String LOG_TAG = PluggedInBroadcastReceiver.class.getSimpleName();
private IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String action = intent.getAction();
if (action != null && action.equals(Intent.ACTION_POWER_CONNECTED)) {
try {
Intent batteryStatusIntent = context.getApplicationContext().registerReceiver(null, iFilter);
double battPercentage = BatteryUtils.getBatteryLevel(batteryStatusIntent);
//Do something with the battery percentage value...
} catch (Exception e) {
Log.e(LOG_TAG, "Battery status intent was null");
}
}
}
}
}
I ran into this error in the past and found that my problems were being caused by the fact that the context that is passed to a Broadcast Receiver does not have the ability have registerReceiver() called on it.
I found some resources that suggest that you can convert the context passed to the Broadcast Receiver to an application context and then call registerReceiver() on the application context. This works for Android versions 4.2 and up, but fails on 4.1.2 (and possibly lower, but haven't tested explicitly). It seems like converting to the application context should allow registerReceiver() to be called, but that doesn't seem to work for all versions of Android.
Does anyone have an explanation for this behavior?
EDIT:
The plot thickens... I've now learned that this crash has occurred on android versions 4.1.1, 4.1.2, 4.3.0 and 5.1.1 over 93% of the crashes occurred on 4.1.2. I'm not sure we're going to find a solution for this, but my fix going forward is to never call registerReceiver() from a BroadcastReceiver. The behavior seems to be undefined and unpredictable even when using the application context which is apparently supposed to allow this.

Service onStartCommand throwing NullPointerException

I have an app that runs two separate services. One of them runs smoothly, and the other works without issue a majority of the time, but is throwing a NullPointerException within onStartCommand() intermittently on a significant number of newer devices (Samsung, HTC, LG) on varying Android versions between 4.1 and 4.4.2. I am unable to reproduce the error on any of my own devices, including two of the exact models which have experienced this issue. The stacktrace is as follows, indicating the problem is on line 145:
java.lang.RuntimeException: Unable to start service com.mycom.myapp.MyLocService#425ab718
with Intent { cmp=com.mycom.myapp/.MyLocService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2695)
at android.app.ActivityThread.access$1900(ActivityThread.java:146)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1337)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5168)
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:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mycom.myapp.MyLocService.onStartCommand(MyLocService.java:145)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2678)
... 10 more
I am using a portion of the code linked within the answer provided here by blackcj to run a location service in the background of my app; here is the relevant snippet from MyLocService.java, with the offending line marked:
#Override
public void onCreate() {
super.onCreate();
mInProgress = false;
mLocationRequest = LocationRequest.create();
servicesAvailable = servicesConnected();
mLocationClient = new LocationClient(this, this, this);
locIntent = new Intent(MY_LOCATION);
}
public int onStartCommand (Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId); // <----- NPE AT LINE 145
setUpLocationClientIfNeeded();
if(!mLocationClient.isConnected() || !mLocationClient.isConnecting()) {
mLocationClient.connect();
}
return START_STICKY;
}
private void setUpLocationClientIfNeeded() {
if(mLocationClient == null) {
mLocationClient = new LocationClient(this, this, this);
}
}
The service is started by the following code within onCreate() in MyActivity.java:
Intent MyLocService = new Intent(this, MyLocService.class);
startService(MyLocService);
The service is declared within the <application> element in AndroidManifest.xml as follows:
<service
android:name=".MyLocService"
android:singleUser="true"
android:stopWithTask="false" >
<intent-filter>
<action android:name="com.mycom.myapp.MyLocService" />
</intent-filter>
</service>
I have been unable to determine what is causing this exception, as it does not happen consistently and I cannot reproduce it myself. What could be causing this intermittent problem?
It appears that returning START_REDELIVER_INTENT instead of START_STICKY has resolved this problem. Instead of continuing to figure out how to check for a null intent, I found a method that supposedly will not cause it in the first place.
I will update with any further conclusions I discover regarding this method as it becomes more widely implemented by my users.

Android , broadcasting parcelable data

I've implemented a class that extends NotificationListenerService which works fine for picking up on notifications posted.
I'm then wanting to take the statusBarNotification object received and broadcast it.
I'd doing the following:
#Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
Intent intent = new Intent();
intent.putExtra("STATUS_BAR_NOTIFICATION",statusBarNotification);
intent.setAction("com.example.NotificationPosted");
sendBroadcast(intent);
}
But when I do this I get the following error:
01-05 01:50:14.333 19574-19673/com.example W/NotificationListenerService[NotificationListener]﹕ Error running onNotificationPosted
java.lang.RuntimeException: Not allowed to write file descriptors here
at android.os.Parcel.nativeAppendFrom(Native Method)
at android.os.Parcel.appendFrom(Parcel.java:431)
at android.os.Bundle.writeToParcel(Bundle.java:1679)
at android.os.Parcel.writeBundle(Parcel.java:636)
at android.app.Notification.writeToParcel(Notification.java:962)
at android.service.notification.StatusBarNotification.writeToParcel(StatusBarNotification.java:106)
at android.os.Parcel.writeParcelable(Parcel.java:1285)
at android.os.Parcel.writeValue(Parcel.java:1204)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:618)
at android.os.Bundle.writeToParcel(Bundle.java:1692)
at android.os.Parcel.writeBundle(Parcel.java:636)
at android.content.Intent.writeToParcel(Intent.java:7013)
at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:2361)
at android.app.ContextImpl.sendBroadcast(ContextImpl.java:1127)
at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:365)
at com.example.NotificationListener.onNotificationPosted(NotificationListener.java:113)
at android.service.notification.NotificationListenerService$INotificationListenerWrapper.onNotificationPosted(NotificationListenerService.java:168)
at android.service.notification.INotificationListener$Stub.onTransact(INotificationListener.java:56)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(Native Method)
Can anyone see what I'm doing wrong, or is this not possible. StatusBarNotification implements Parcelable
I've had the same problem with notifications from Twitter.
I successfully solved it setting the notification's extras to null.
Try this:
#Override
#SuppressLint("NewApi") // Notification.extras is only available in API Level 19+
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
// Apprarently, the bug is caused by the extras when they're written to the parcel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
statusBarNotification.getNotification().extras = null;
}
Intent intent = new Intent();
intent.putExtra("STATUS_BAR_NOTIFICATION",statusBarNotification);
intent.setAction("com.example.NotificationPosted");
sendBroadcast(intent);
}
Please note that this solution could break the functionality of notification's app if you send the contentIntent (the app could think the extras are there without checking).
This is probably some kind of android bug as some users noted above. If you want to get around it and still use as much bundle as possible consider implementing custom bundle serializer/deserializer. I already answered a question how to build such thing in How to serialize a Bundle?
and what is missing is how to actually use it when packing/unpacking the parcel. This is described here:
#Override public void writeToParcel(Parcel dest, int flags) {
byte[] bytes = serializeBundle(yourBundle);
dest.writeInt(bytes.length);
dest.writeByteArray(bytes);
}
and then
YourConstructor(Parcel in) {
byte[] bytes = new byte[in.readInt()]; // read the length of the array
in.readByteArray(bytes); // read bytes to array
yourBundle = deserializeBundle(bytes); // unpack the bundle
}
I have crash only kitkat(api 19). Му error(show all error scrooling to right):
Error running onNotificationPosted
java.lang.AbstractMethodError: abstract method not implemented
at android.service.notification.NotificationListenerService.onNotificationPosted(NotificationListenerService.java)
at service.CustomNotificationListenerService.onNotificationPosted(CustomNotificationListenerService.kt:46)
at android.service.notification.NotificationListenerService$INotificationListenerWrapper.onNotificationPosted(NotificationListenerService.java:168)
at android.service.notification.INotificationListener$Stub.onTransact(INotificationListener.java:56)
at android.os.Binder.execTransact(Binder.java:404) at dalvik.system.NativeStart.run(Native Method)
Simple Solve: i removed method: super()
This solution worked for me:
#Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
Bundle bundle = new Bundle(); statusBarNotification.getNotification().extras.putBundle("android.car.EXTENSIONS", bundle);
Intent intent = new Intent();
intent.putExtra("STATUS_BAR_NOTIFICATION",statusBarNotification);
intent.setAction("com.example.NotificationPosted");
sendBroadcast(intent);
}

Categories

Resources