title: How to get Android Application to push notifications after ui thread is closed
body: <p><strong>How to get push notification working after manually closing UI on Android?</strong></p>
  
  <p>Hi, I need some help, Couldn't find any solutions by searching.</p>
  
  <p>Application basically is like any other messaging applications, ex. Whatsapp.</p>
  
  <p>I have <strong>MessageService</strong> running <strong>as own process</strong>, even UI closed, it stays alive.</p>
  
  <p>This is how my application basically works:</p>
  
  <ol>
  <li><strong>MainActivity</strong> start service </li>
  <li><strong>MessageService</strong> send broadCast to </li>
  <li><strong>messageReceiver</strong> gets broadCast and run messageLoader</li>
  <li><strong>MessagesLoader</strong> extends <strong>AsyncTask</strong> gets changes from database</li>
  <li><strong>MessagesLoader</strong> push notification. </li>
  </ol>
  
  <p>Every these parts <strong>working correctly</strong> when <strong>UI running</strong></p>
  
  <p>When I close UI, messageService restarts again, but no push notifications after UI closed. </p>
  
  <p><strong>Any help to get this work would be appreciated.</strong></p>
  
  <p><strong>Thanks</strong></p>
  
  <p>Here is some code snippet to understand how my thing works..</p>
  
  <p><strong>MainActivity.java</strong></p>
  
  <pre><code>    ...........................
      @Override
      protected void onResume() {
          super.onResume();
          serviceIntent = new Intent(getApplicationContext(), MessageService.class);
          startService(serviceIntent);
  
          registerReceiver(messageReceiver, new IntentFilter(MessageService.MESSAGES_BROADCAST_ACTION));
      }
      ...........................
  </code></pre>
  
  <p><strong>MessageService.java</strong></p>
  
  <pre><code>public class MessageService extends Service {
      Updater updater;
      BroadcastReceiver messageBroadcaster;
      Intent intent;
      Context context;
      static final public String MESSAGES_BROADCAST_ACTION = "com.&lt;Your Package&gt;";
  
      public MessageService() {
      }
  
      @Override
      public IBinder onBind(Intent intent) {
          this.intent = intent;
          throw new UnsupportedOperationException("Not yet implemented");
      }
  
      @Override
      public void onCreate() {
          super.onCreate();
          this.updater = new Updater();
          this.context = getApplicationContext();
          this.intent = new Intent(this, NotificationActivity.class);
          Toast.makeText(this, "Message Service Created", Toast.LENGTH_LONG).show();
      }
  
      @Override
      public synchronized int onStartCommand(Intent intent, int flags, int startId) {
  
          if (!updater.isRunning()) {
              updater.start();
              updater.isRunning = true;
          }
  
          return super.onStartCommand(intent, flags, startId);
      }
  
      @Override
      public synchronized void onDestroy() {
          super.onDestroy();
  
          if (updater.isRunning) {
              updater.interrupt();
              updater.isRunning = false;
              updater = null;
          }
          Toast.makeText(this, "Message Service Destroyed", Toast.LENGTH_LONG).show();
      }
      class Updater extends Thread {
  
          public boolean isRunning = false;
          public long DELAY = 2500;
  
          @Override
          public void run() {
              super.run();
  
              isRunning = true;
              while (isRunning) {
                  sendResult();
                  try {
                      Thread.sleep(DELAY);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                      isRunning = false;
                  }
              }
          }
  
          public boolean isRunning() {
              return this.isRunning;
          }
      }
  
      public void sendResult() {
          sendBroadcast(intent);
      }
  }
  </code></pre>
  
  <p><strong>MessageReceiver.java</strong></p>
  
  <pre><code>public class MessageReceiver extends BroadcastReceiver {
      public void onReceive(Context context, Intent intent) {
  
          Intent serviceIntent = new Intent(context, MessageService.class);
          context.startService(serviceIntent);
          new MessagesLoader(context).execute();
      }
  }
  </code></pre>
  
  <p><strong>MessageLoader.java</strong></p>
  
  <pre><code>public class MessagesLoader extends AsyncTask&lt;String,Void,String&gt; {
      public MessagesLoader(Context context) {
          this.context = context;
          this.intent = new Intent(this.context, ChatsActivity.class);
          this.prev_count = prev_count;
  
          Intent intent = new Intent(context, ChatsActivity.class);
          PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
  
  
          this.mBuilder = new android.support.v4.app.NotificationCompat.Builder(context)
                          .setSmallIcon(R.mipmap.ic_launcher)
                          .setContentTitle("YOUR APP");
      }
  
      protected void onPreExecute(){
      }
  
      @Override
      protected String doInBackground(String... arg0) {
          StringBuffer result = new StringBuffer("");
  
          try {
  
              URL url = new URL("http://yourURL.com/get_data.php");
              HttpURLConnection con = (HttpURLConnection)url.openConnection();
  
              con.setRequestMethod("POST");
              con.setRequestProperty("User-Agent", "");
              con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  
              con.setDoOutput(true);
  
              String urlParameters = "&lt;OWN PARAMETERS&gt;";
              DataOutputStream wr = new DataOutputStream(con.getOutputStream());
              wr.writeBytes(urlParameters);
              wr.flush();
              wr.close();
  
              int responseCode = con.getResponseCode();
  
              con.connect();
  
              InputStream inputStream = con.getInputStream();
  
              BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
              String line = "";
  
              while ((line = rd.readLine()) != null) {
                  result.append(line);
              }
              return new String(result);
          } catch(Exception e){
              return new String("Exception: " + e.getMessage());
          }
      }
  
      @Override
      protected void onPostExecute(String result) {
          initData(result);
      }
  
      public void initData(String result) {
          // Actually Store Data to sharedPreferences
          String error = "";
          JSONObject obj = new JSONObject();
          // ...ETC
  
          int count = 5;
          showNotification(5);
      }
  
  
      public void showNotification(int count) {
  
          NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  
          Intent mIntent = new Intent(this.context, ChatsActivity.class);
          PendingIntent pIntent = PendingIntent.getActivity(this.context, 0, mIntent, 0);
  
          Intent cIntent = new Intent(this.context, NotificationActionService.class);
          PendingIntent cPIntent = PendingIntent.getService(this.context, 0, cIntent, 0);
          NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
          bigTextStyle.bigText("YOUR BIG TEXT");
          Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          mBuilder
              .setContentIntent(pIntent)
              .setContentText("YOUR CONTENT TEXT")
              .setAutoCancel(true)
              .setLights(R.color.white, 1000, 500)
              .setSound(soundUri)
              .setGroup("YOUR GROUP")
              .setTicker("YOUR TICKER TEXT")
              .setWhen(System.currentTimeMillis())
              .setCategory("YOUR CATEGORY")
  
               .setStyle(bigTextStyle)
               .addAction(0, "Show Messages", pIntent);
  
          TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
          stackBuilder.addParentStack(MainActivity.class);
          stackBuilder.addNextIntent(mIntent);
          PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
          mBuilder.setContentIntent(resultPendingIntent);
      }
  }
  </code></pre>
  
  <p><strong>AndroidManifest.xml</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.yourpackage" &gt;
  android:versionCode="1"
  android:versionName="1.0"
  android:permission="android.permission.RECEIVE_BOOT_COMPLETED"&gt;
  
  &lt;uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" /&gt;
  &lt;uses-permission android:name="android.permission.INTERNET"/&gt;
  &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
  &lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /&gt;
  &lt;uses-feature android:name="android.hardware.camera" android:required="true" /&gt;
  &lt;application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:configChanges="orientation"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" &gt;
      &lt;activity
          android:name="com.yourpackage.MainActivity"
          android:label="@string/app_name"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="android.intent.action.MAIN" /&gt;
          &lt;/intent-filter&gt;
      &lt;/activity&gt;
  
      &lt;service android:name="com.yourpackage.MessageService"
          android:process=":messageService"
          android:enabled="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/messageService"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="com.yourpackage.MessageService" /&gt;
          &lt;/intent-filter&gt;
      &lt;/service&gt;
  
      &lt;receiver android:name="com.yourpackage.MessageReceiver"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="com.yourpackage.MessageReceiver" /&gt;
          &lt;/intent-filter&gt;
      &lt;/receiver&gt;
  
  &lt;/application&gt;
  &lt;/manifest&gt;
  </code></pre>