/*
    Copyright 2013-2014 appPlant UG

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

package de.appplant.cordova.plugin.background;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Puts the service in a foreground state, where the system considers it to be
 * something the user is actively aware of and thus not a candidate for killing
 * when low on memory.
 */
public class ForegroundService extends Service {

    // Fixed ID for the 'foreground' notification
    private static final int NOTIFICATION_ID = -574543954;

    // Scheduler to exec periodic tasks
    final Timer scheduler = new Timer();

    // Used to keep the app alive
    TimerTask keepAliveTask;

    /**
     * Allow clients to call on to the service.
     */
    @Override
    public IBinder onBind (Intent intent) {
        return null;
    }

    /**
     * Put the service in a foreground state to prevent app from being killed
     * by the OS.
     */
    @Override
    public void onCreate () {
        super.onCreate();
        keepAwake();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sleepWell();
    }

    /**
     * Put the service in a foreground state to prevent app from being killed
     * by the OS.
     */
    public void keepAwake() {
        final Handler handler = new Handler();

        startForeground(NOTIFICATION_ID, makeNotification());

        keepAliveTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        // Nothing to do here
                        // Log.d("BackgroundMode", "" + new Date().getTime());
                    }
                });
            }
        };

        scheduler.schedule(keepAliveTask, 0, 1000);
    }

    /**
     * Stop background mode.
     */
    private void sleepWell() {
        stopForeground(true);
        keepAliveTask.cancel();
    }

    /**
     * Create a notification as the visible part to be able to put the service
     * in a foreground state.
     *
     * @return
     *      A local ongoing notification which pending intent is bound to the
     *      main activity.
     */
    @SuppressWarnings("deprecation")
    private Notification makeNotification() {
        Context context = getApplicationContext();
        String pkgName  = context.getPackageName();
        Intent intent   = context.getPackageManager()
                .getLaunchIntentForPackage(pkgName);

        PendingIntent contentIntent = PendingIntent.getActivity(
                context, NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        JSONObject settings = BackgroundMode.settings;

        Notification.Builder notification = new Notification.Builder(context)
                .setContentTitle(settings.optString("title"))
                .setContentText(settings.optString("text"))
                .setTicker(settings.optString("ticker"))
                .setOngoing(true)
                .setSmallIcon(getIconResId());

        if (settings.optBoolean("resume")) {
            notification.setContentIntent(contentIntent);
        }

        if (Build.VERSION.SDK_INT < 16) {
            // Build notification for HoneyComb to ICS
            return notification.getNotification();
        } else {
            // Notification for Jellybean and above
            return notification.build();
        }
    }

    /**
     * Retrieves the resource ID of the app icon.
     *
     * @return
     *      The resource ID of the app icon
     */
    private int getIconResId () {
        Context context = getApplicationContext();
        Resources res   = context.getResources();
        String pkgName  = context.getPackageName();

        int resId;
        resId = res.getIdentifier("icon", "drawable", pkgName);

        return resId;
    }
}

@@ -843,16 +843,17 @@
 icense.%0A
+ 
 */%0A%0Apack
@@ -896,16 +896,138 @@
 round;%0A%0A
+import java.util.Timer;%0Aimport java.util.TimerTask;%0A%0Aimport org.json.JSONObject;%0A%0Aimport android.annotation.SuppressLint;%0A
 import a
@@ -1296,169 +1296,8 @@
 der;
-%0Aimport android.util.Log;%0A%0Aimport org.json.JSONException;%0Aimport org.json.JSONObject;%0A%0Aimport java.util.Date;%0Aimport java.util.Timer;%0Aimport java.util.TimerTask;
 %0A%0A/*
@@ -2640,24 +2640,54 @@
 unnable() %7B%0A
+                    @Override%0A
             
@@ -3359,24 +3359,52 @@
 ty.%0A     */%0A
+    @SuppressLint(%22NewApi%22)%0A
     @Suppres
@@ -3470,24 +3470,79 @@
 ication() %7B%0A
+        JSONObject settings = BackgroundMode.settings;%0A
         Cont
@@ -3545,32 +3545,36 @@
 Context context 
+    
 = getApplication
@@ -3600,32 +3600,36 @@
 String pkgName  
+    
 = context.getPac
@@ -3664,16 +3664,20 @@
 ntent   
+    
 = contex
@@ -3756,216 +3756,8 @@
 );%0A%0A
-        PendingIntent contentIntent = PendingIntent.getActivity(%0A                context, NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);%0A%0A        JSONObject settings = BackgroundMode.settings;%0A%0A
     
@@ -3830,24 +3830,16 @@
 ontext)%0A
-        
         
@@ -3881,27 +3881,23 @@
 (%22title%22
-))%0A        
+, %22%22))%0A
         
@@ -3937,16 +3937,20 @@
 g(%22text%22
+, %22%22
 ))%0A     
@@ -3948,32 +3948,24 @@
 %22))%0A        
-  
-      
 .setTicker(s
@@ -3994,25 +3994,23 @@
 ker%22
-))%0A      
+, %22%22))%0A
         
   .s
@@ -4001,26 +4001,24 @@
 %22))%0A        
-  
 .setOngoing(
@@ -4023,24 +4023,16 @@
 g(true)%0A
-        
         
@@ -4075,16 +4075,34 @@
     if (
+intent != null && 
 settings
@@ -4122,24 +4122,185 @@
 resume%22)) %7B%0A
+%0A            PendingIntent contentIntent = PendingIntent.getActivity(%0A                    context, NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);%0A%0A
             

Fix null pointer exception if launch intent may be null