Hustler
Hustler

Reputation: 13

How to create notifications while app is minimized in android?

I have been working on this code using the NotificationManager class to make a notification.

However, I want to display notifications even when the app is in background. Any ideas?

  @Override
  protected void onPostExecute(String result) {
      try
      {
           Thread t=new Thread()
          {
            public void run()
            {
                try
                {

                        JSONObject jsonResponse = new JSONObject(jsonResult);
                        JSONArray jsonMainNode = jsonResponse.optJSONArray("user");
                        for (int i = 0; i < jsonMainNode.length(); i++) 
                        {
                            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                            String name = jsonChildNode.optString("userid");
                            String number = jsonChildNode.optString("unreadmesage");
                            Thread.sleep(5000);
                            NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                            Notification n=new Notification(R.drawable.mainicon,"New Msg From ASKCOTTON",System.currentTimeMillis());
                            //n.defaults=n.FLAG_ONLY_ALERT_ONCE+Notification.FLAG_AUTO_CANCEL;
                            Intent in=new Intent(getApplicationContext(),message.class);
                            PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, in, 0);
                           // n.flags |= Notification.FLAG_ONGOING_EVENT;
                            n.setLatestEventInfo(getBaseContext(), "ASKCOTTON", "You Have New Message(s)", pi);
                            nm.notify(1,n);
                        }
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
          };t.start();

      }catch(Exception e)
      {

      }
  }

Upvotes: 0

Views: 1496

Answers (1)

Machado
Machado

Reputation: 14499

You have to build a Service class.

The Service will run in background even if your application is minimized. It will build your notifications and send them through the NotificationManager.

Take a look at this link: http://it-ride.blogspot.it/2010/10/android-implementing-notification.html

Upvotes: 1

Related Questions