0

Here is my project structure...

enter image description here

Let me tell you how it works. When I open app it creates a never ending background service namely "Exampleservice". This service executes a async class "firebaseOp" The job of "firebaseOp" is to get data from "Member" class methods and post it to database.

Now after database operation is completed, I want to show a notification to user.

The keypoint here is the app will be close after starting the service and service will run in background. The service is running fine and doing the job but the How can I show that notification?

I have tried some codes but getting null object reference error.

Here is the ExampleService class (if needed) ....

package com.example.btc;

import android.app.Service;

import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class ExampleService extends Service {


        @Override
        public void onCreate() {

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Toast.makeText(this, "Service STARTING", Toast.LENGTH_SHORT).show();


          Thread thread = new Thread() {
                @Override
                public void run() {
                    while(true) {
                        try {
                            Thread.sleep(60000);
                            firebaseOp Op = new firebaseOp();
                            Op.execute();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

            };





};
            thread.start();
            return START_STICKY;

        }

        @Override
        public IBinder onBind(Intent intent) {
            // We don't provide binding, so return null
            return null;
        }

        @Override
        public void onDestroy() {
            Toast.makeText(this, "Destroyed", Toast.LENGTH_SHORT).show();
        }
    }

1 Answers1

0

These codes are about showing notifications.Add it where it is needed.

Notification.Builder builder =new Notification.Builder(MainActivity.this);
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent push =new Intent(MainActivity.this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this,0,push,0);
builder.setContentTitle("My notification")
       .setContentText("Hello World!")
       .setContentIntent(contentIntent)
       .setTicker("New message")
       .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher))
       .setDefaults(Notification.DEFAULT_ALL);
       .setSmallIcon(R.drawable.ic_launcher);
       Notification notify = builder.build();
       mNotifyMgr.notify(1,notify);
igarasi
  • 137
  • 7