Search code examples
androidservice

How to show status notification or popup dialog from background service?


I have created bootup Service which listen for incoming messages in my application. Service is continuosly running in backgroung thought application is closed that is user goes offline. While user is offline and there is new message I have to show notifiacation on status bar or popup dialog(Here in this situaction service is not bound to any of Activity). I am facing following problems:

  1. While creating notification I am not getting Context and Activity.
  2. While I am displaying dialog from service class I am getting exception as "Can't create handler inside thread that has not called Looper.prepare()".

I am new one for android services part and don't know hoe to solve this. Can anybody guide me how to do this? Is there any link which will guide me for this? I got stucked due to this problem. Help highly appreciated. Thanks.


Solution

  • You can send a notification and specify what Activity should be run when user initiates it:

     private void sendNotification(Bundle bundle){
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        int icon = R.drawable.icon;
        CharSequence tickerText = "bla bla";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello World!";
        Intent notificationIntent = new Intent(this, ACTIVITY_YOU_WANT_TO_START.class);
        if(bundle!=null)
            notificationIntent.putExtras(bundle); //you may put bundle or not
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        int any_ID_you_want = 1; 
        //if you send another notification with same ID, this will be replaced by the other one
        mNotificationManager.notify(HELLO_ID, notification);
    }
    
    //To play a sound add this:
    notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3"); //for example
    

    You can start another Activity:

    private boolean startActivity(Bundle bundle){
        Intent myIntent = new Intent(mContext, ACTIVITY_YOU_WANT_TO_START.class);
        if(bundle!=null)
             myIntent.putExtras(bundle);//optional
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(myIntent);
        return true;
    }