Search code examples
androidandroid-intentbroadcastreceiveralarmmanagerandroid-pendingintent

NullPointerException while sending Intent from Broadcast Receiver to Services when App is in background


I am working on an App for which I am setting an alarm with alarmManager and when broadcast receiver received the pending intent I passed it into Service class to show a notification.and also passing an intent to check which type to alarm is being received.but when my app is in background it stops working because it received null value from intent. Here is my code :

In MainActivity.java :

     @Override
      protected Dialog onCreateDialog(int id) {

            if (id == DIALOG_ID) {
        return new TimePickerDialog(MainActivity.this, kTimePickerListener, 
        hour, min, false);
       }
          return null;
       }

         protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
           new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker timePicker, int hourofday, int 
        minutes) {
            hour = hourofday;
            min = minutes;

            Calendar calendar = Calendar.getInstance();

            // set selected time from timepicker to calendar

            calendar.set(Calendar.HOUR_OF_DAY, hour);
            calendar.set(Calendar.MINUTE, minutes);

            Intent myIntent = new Intent(MainActivity.this, 
            ServiceManager.class);
            myIntent.putExtra("reqcode", 11);

            // A PendingIntent specifies an action to take in the
            // future
            PendingIntent mPendingIntent = 
            PendingIntent.getBroadcast(MainActivity.this, 11, myIntent, 0);

            // set alarm time
             alarmManager = (AlarmManager) MainActivity.this
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), 
           mPendingIntent);

        }
    };

i am sending a pending code with request code 11 and also sending an intent through pendingintent with myIntent.putExtra("reqcode", 11);

In my ServiceManager.class :

            public class ServiceManager extends BroadcastReceiver 
            {

            @Override
            public void onReceive(Context context, Intent intent) {

            int Noti_code = intent.getIntExtra("reqcode",-1);

            Intent myIntent = new Intent(context,NotificationService.class);
                  myIntent.putExtra("reqcode", Noti_code);
                  context.startService(myIntent);
              }
            }

Here I am getting this code as a Noti_code passing it to my NotificationServices.class through Intent.

Here is NotificationServices.class :

         public class NotificationService extends Service {

         private NotificationManager mManager;

         @Override
           public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
              return null;
             }

         @Override
          public void onCreate() {
           super.onCreate();
           }

         @SuppressWarnings({"static-access", "deprecation"})
         @Override
         public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);

    **int Noti_Code = intent.getIntExtra("reqcode",-2);** //App crashes here

       if (Noti_Code == 11) {
    mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
    ShowNotification(getApplicationContext(), mManager);
}
           }

         @Override
          public void onDestroy() {
           // TODO Auto-generated method stub
            super.onDestroy();
              }
            }

When my app is in backgroud it crashes here int Noti_Code = intent.getIntExtra("reqcode",-2);

Here is my Menifest.xml :

             <uses-permission android:name="android.permission.WAKE_LOCK" />

           <application
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:roundIcon="@mipmap/ic_launcher_round"
              android:supportsRtl="true"
              android:theme="@style/AppTheme">
          <activity android:name=".MainActivity">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>
      <activity android:name=".Activity_detail" />
      <activity android:name=".History" />

      <service
        android:name=".NotificationService"
        android:enabled="true"
        android:exported="true"
        android:stopWithTask="false"/>
     <receiver android:name=".ServiceManager"/>
     </application>

And Here is the Logcat:

     Process: com.spendless.spendless_financiallifestylesavingapp, PID: 3910                                                                     
     java.lang.RuntimeException: Unable to start service 
     com.spendless.spendless_financiallifestylesavingapp.Services.NotificationService@5f7f8c2 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)
                                                                                                   at android.app.ActivityThread.access$2200(ActivityThread.java)
                                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                                                                                                   at android.os.Handler.dispatchMessage(Handler.java)
                                                                                                   at android.os.Looper.loop(Looper.java)
                                                                                                   at android.app.ActivityThread.main(ActivityThread.java)
                                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                                                                                                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.spendless.spendless_financiallifestylesavingapp.Services.NotificationService.onStart(NotificationService.java:46)
                                                                                                   at android.app.Service.onStartCommand(Service.java)
                                                                                                   at android.app.ActivityThread.handleServiceArgs(ActivityThread.java) 
                                                                                                   at android.app.ActivityThread.access$2200(ActivityThread.java) 
                                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java) 
                                                                                                   at android.os.Handler.dispatchMessage(Handler.java) 
                                                                                                   at android.os.Looper.loop(Looper.java) 
                                                                                                   at android.app.ActivityThread.main(ActivityThread.java) 
                                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java) 
                                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java) 

Please help me if there is something missing in my code? Thanks.


Solution

  • You have implemented onStart() in your Service. This is not the correct method. You should implement onStartCommand(). The return value from onStartCommand() tells Android whether or not to restart your Service under certain conditions and how to redeliver any Intents. Using onStart() has some backwards compatibility support that automatically provides the value START_STICKY to control restart of your Service. This tells Android that you want your Service restarted all the time.

    What you are probably seeing is that Android has restarted your Service with a null Intent. This can happen if Android kills your Service and then automatically restarts it (since you return START_STICKY).

    See the documentation on Service and also onStart() and onStartCommand().