• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Can't Update Notifications text after Forerground service init; Context issue

iamjkdn

Lurker
Aug 19, 2018
1
0
Hello
I have a simple NanoHTTPD server running in Android. It serves music files from the storage.

I have created a Foreground service to make it running. Now this part works. It also shows the notification in the panel.

But I am having trouble updating the notification with new text. Basically I just want to display the new icoming file request URL in the notification. How can I do that?

I tried using Notification.notify() but the I cant understand the context to pass in the non-activity java file which defines the NanoHTTPD server.

File structure
- Mainactivity
- NanoServer (server implementaion)
- NanoService (foreground service class)
- NotificationProvider (separate class to handle notifications)

NanoServer.java
Java:
public class NanoServer extends NanoHTTPD {
    public Context context = getContext();
    public NotificationProvider notificationProvider;

    public NanoServer(int port) {
        super(8089);
    }

    @Override
    public Response serve(String uri, Method method,
                          Map<String, String> header, Map<String, String> parameters,
                          Map<String, String> files) {
        String answer = "";
        String msg;

        // doesnt work with the context. something wrong here I guess????
        notificationProvider = new NotificationProvider();
        notificationProvider.setNotification(context, "Title", uri, 0);

        FileInputStream fis = null;

        try {
            fis = new FileInputStream(uri);
            Log.w(TAG, uri + " found");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return newChunkedResponse(Status.OK, "audio/mpeg", fis);

    }

    public Context getContext() {
        return context;
    }
}

NanoService.java
Java:
    String TAG = "NANOSERVICE";
    public Context context = this;
    public Handler handler = null;
    public static Runnable runnable = null;
    PowerManager powerManager;
    PowerManager.WakeLock wakeLock;
    WifiManager.WifiLock wifiLock;

    private NanoServer nanoServer;
    public NotificationProvider notificationProvider;

    public NanoService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Start the httpd.
        try {
            nanoServer = new NanoServer(8089);
            nanoServer.start();
            Log.d(TAG, "Service with server started");
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Service failed to start.", Toast.LENGTH_LONG).show();
        }

        // Keep the CPU awake (but not the screen).
        powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();

        // Keep the WIFI turned on.
        WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TAG);
        wifiLock.acquire();

        notificationProvider = new NotificationProvider();
        notificationProvider.setNotification(this, "Title", "Message", 0);

        // had to extend notificationprovider with notification
        startForeground(1, notificationProvider);
        Log.d(TAG, "Foreground service running");

        return Service.START_STICKY;

    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        wakeLock.release();
        wifiLock.release();
        nanoServer.stop();
    }

NotificationProvider.java
Java:
public class NotificationProvider extends Notification {
    String TAG = "NOTIFICATIONPROVIDER";
    public NotificationProvider() {
    }

    public void setNotification(Context context, String notificationTitle, String notificationMessage, int notificationRequestCode){
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle(notificationTitle)
                        .setContentText(notificationMessage)
                        .setTicker("My service")
                        .setColor(101)
                        .setWhen(System.currentTimeMillis())
                        .setOngoing(true)
                        .setPriority(NotificationCompat.PRIORITY_MAX);

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, notificationRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
        Log.d(TAG, "Got new Notification");
    }
}
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones