title: How to get context in service outside of onStartCommand() method?
body: <p>When I use Intent outside of onStartCommand() of service, to show notification on a specific event, it shows getApplicationContext on the null object reference.
  Service only allow to use getApplcationContext/this/context inside the onStartCommand() method.
  How can I use it outside of onStartCommand() method?
  Below is my Service. Can someone help me out with this?</p>
  
  <pre><code>public class ForegroundService extends Service {
      @Nullable
  
      private static TransferUtility transferUtility;
      private static ArrayList&lt;HashMap&lt;String, Object&gt;&gt; transferRecordMaps;
      private static ArrayList&lt;HashMap&lt;String, Object&gt;&gt; transferRecordMaps1;
      private Utils utils = new Utils();
      private static final int INDEX_NOT_CHECKED = -1;
      public static int totalcount, totalAssetCount;
      private int checkedIndex;
      private static List&lt;TransferObserver&gt; observers;
      private static int REQUEST_CAMERA = 0, navigate = 0,counter=0,failedcounter=0;
      private static final String LOG_TAG = "ForegroundService";
      UploadMediaToAssetFragment uploadMediaToAssetFragment;
      private int progress;
      Context context;
      private long currentbyte, totalbyte;
      private Notification notification;
  
  
      @Override
      public void onCreate() {
          super.onCreate();
          transferUtility = Util.getTransferUtility(getApplicationContext());
          checkedIndex = INDEX_NOT_CHECKED;
          transferRecordMaps = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;();
          transferRecordMaps1 = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;();
  
          uploadMediaToAssetFragment = new UploadMediaToAssetFragment();
  
  
      }
  
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
              Log.i(LOG_TAG, "Received Start Foreground Intent ");
              Intent notificationIntent = new Intent(this, UploadMediaToAssetFragment.class);
              notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
              notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                      | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  
              Log.d(LOG_TAG,"bytes"+UploadMediaToAssetFragment.totalAssetCount+ " total"+UploadMediaToAssetFragment.totalcount);
  
              uploadAsset();
              initData();
              updateList();
  //            AlertDialog.Builder builder = new AlertDialog.Builder(this);
  //                    builder.setTitle("Test dialog");
  //                    builder.setIcon(R.drawable.icon);
  //                    builder.setMessage("Content");
  //
  //                        AlertDialog alert = builder.create();
  //            alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
  //                alert.show();
  
              // startActivity(notificationIntent);
              PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                      notificationIntent, 0);
  
              Intent previousIntent = new Intent(this, ForegroundService.class);
              previousIntent.setAction(Constants.ACTION.PREV_ACTION);
              PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                      previousIntent, 0);
  
              Intent playIntent = new Intent(this, ForegroundService.class);
              playIntent.setAction(Constants.ACTION.PLAY_ACTION);
              PendingIntent pplayIntent = PendingIntent.getService(this, 0,
                      playIntent, 0);
  
              Intent nextIntent = new Intent(this, ForegroundService.class);
              nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
              PendingIntent pnextIntent = PendingIntent.getService(this, 0,
                      nextIntent, 0);
  
              Bitmap icon = BitmapFactory.decodeResource(getResources(),
                      R.drawable.logo);
               notification = new NotificationCompat.Builder(this)
                      .setContentTitle("Visibly")
                      .setTicker("asset uplaoding")
                      .setContentText("uploading")
                      .setSmallIcon(R.drawable.ic_launcher)
                      .setLargeIcon(
                              Bitmap.createScaledBitmap(icon, 128, 128, false))
                      .setContentIntent(pendingIntent)
                      .setOngoing(true)
                       .setProgress(100,progress,false)
                      .addAction(android.R.drawable.ic_menu_close_clear_cancel,
                              "cancel", ppreviousIntent).build();
              startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
                      notification);
  
  //            if(UploadMediaToAssetFragment.totalAssetCount&gt;=UploadMediaToAssetFragment.totalcount)
  //            {
  //                onDestroy();
  //                stopForeground(true);
  //                stopSelf();
  //            }
          } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
              Log.i(LOG_TAG, "Clicked Previous");
          } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
              Log.i(LOG_TAG, "Clicked Play");
          } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
              Log.i(LOG_TAG, "Clicked Next");
          } else if (intent.getAction().equals(
                  Constants.ACTION.STOPFOREGROUND_ACTION)) {
              Log.i(LOG_TAG, "Received Stop Foreground Intent");
              stopForeground(true);
              stopSelf();
          }
  
          return START_STICKY;
      }
  
      @Override
      public void onDestroy() {
          super.onDestroy();
          Log.i(LOG_TAG, "In onDestroy");
      }
      public IBinder onBind(Intent intent) {
          return null;
      }
  
      public class ForegroundServiceBInder extends Binder {
          ForegroundService getService() {
              // Return this instance of LocalService so clients can call public methods
              return ForegroundService.this;
          }
      }
  
  
      public void uploadAsset()
      {
          Log.d("upload asset service","method called");
          for(int i=0;i&lt;AddMediaAssetActivity.galleryDTOArrayList1.size();i++)
          {
              Handler handler1 = new Handler();
              try {
                  if(AddMediaAssetActivity.galleryDTOArrayList1.get(i)!=null)
                  {
                      String path;
                      Uri uri = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getMediaName()));
                      path = Utility.getPath(uri, getApplicationContext());
                      Uri uriThumb = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getThumbnail()));
                      String pathThum = null;
                      if (uriThumb != null)
                          pathThum = Utility.getPath(uriThumb, getApplicationContext());
                      path = Utility.getPath(uri, getApplicationContext());
                      if(GlobalVariables.isNetworkAvailable(getApplicationContext())) {
                          beginUpload1(pathThum, pathThum);
  
                          beginUpload(path, AddMediaAssetActivity.galleryDTOArrayList1.get(i).getDescription(), pathThum,AddMediaAssetActivity.galleryDTOArrayList1.get(i).getCreateTagPostDTOList());
                      }else
                      {
                          AlertDialog.Builder builder;
                          if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) {
                              builder = new AlertDialog.Builder(getApplicationContext(),android.R.style.Theme_Material_Light_Dialog_Alert);
                          } else {
                              builder = new AlertDialog.Builder(getApplicationContext());
                          }
                          builder.setMessage(getResources().getString(R.string.network_connectivity))
                                  .setTitle("");
                          builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialog, int id)
                              {
                                  //getApplicationContext().finish();
                                  dialog.dismiss();
                              }
                          });
                          AlertDialog dialog = builder.create();
                          dialog.setCanceledOnTouchOutside(true);
                          dialog.show();
                          dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.clear_blue));
  
                      }
                  }
              }catch (Exception e)
              {
  
              }
          }
      }
  
      /*
       * Begins to upload the file specified by the file path.
       */
      private void beginUpload(String filePath, String title, String pathThum, List&lt;TagDTO&gt; createTagPostDTOList)
      {
          Log.d("beginUpload","method called "+filePath+" title "+title+" pathnum "+pathThum+" list tagdto"+createTagPostDTOList);
          if (filePath == null) {
              Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
                      Toast.LENGTH_LONG).show();
              return;
          }
          File file = new File(filePath);
          TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
                  file, CannedAccessControlList.PublicRead);
          File file1 = new File(pathThum);
          AssetMediaDTO assetMediaDTO=new AssetMediaDTO();
          if(GlobalVariables.isCampaignAsset)
          {
              if (GlobalVariables.campaignFeedDTO.getCampaign_category() != null &amp;&amp; GlobalVariables.campaignFeedDTO.getCampaign_category().length() &gt; 0 &amp;&amp; !(GlobalVariables.campaignFeedDTO.getCampaign_category().equalsIgnoreCase("null"))) {
                  assetMediaDTO.setCategory_id(GlobalVariables.campaignFeedDTO.getCampaign_category());
              } else {
                  assetMediaDTO.setCategory_id("rpPDp");
              }
              if (GlobalVariables.campaignFeedDTO.getCampaign_folder() != null &amp;&amp; GlobalVariables.campaignFeedDTO.getCampaign_folder().length() &gt; 0 &amp;&amp; !(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("null"))) {
                  if(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("General"))
                  {
                      assetMediaDTO.setFolder_id("");
                  }else
                  {
                      assetMediaDTO.setFolder_id(GlobalVariables.campaignFeedDTO.getCampaign_folder());
                  }
  
  
              } else
              {
                  assetMediaDTO.setFolder_id("");
  
              }
          }else
          {
              if (AssetFolderActivity.folderDTO.getCategoryID() != null &amp;&amp; AssetFolderActivity.folderDTO.getCategoryID().length() &gt; 0 &amp;&amp; !(AssetFolderActivity.folderDTO.getCategoryID().equalsIgnoreCase("null"))) {
                  assetMediaDTO.setCategory_id(AssetFolderActivity.folderDTO.getCategoryID());
              } else {
                  assetMediaDTO.setCategory_id("rpPDp");
              }
              if (AssetFolderActivity.folderDTO.getFolderIdentity() != null &amp;&amp; AssetFolderActivity.folderDTO.getFolderIdentity().length() &gt; 0 &amp;&amp; !(AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("null"))) {
  
                  if(AssetFolderActivity.folderDTO.getFoldername()!=null&amp;&amp;AssetFolderActivity.folderDTO.getFoldername().equalsIgnoreCase("general"))
                  {
                      assetMediaDTO.setFolder_id("");
                  }else {
                      assetMediaDTO.setFolder_id(AssetFolderActivity.folderDTO.getFolderIdentity());
                  }
  
              } else {
                  assetMediaDTO.setFolder_id("");
  
              }
          }
          assetMediaDTO.setMedia_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file.getName());
          assetMediaDTO.setThumbnail_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file1.getName());
          try {
              assetMediaDTO.setMediaSize(""+file.length());
          }catch (Exception e)
          {
  
          }
          assetMediaDTO.setDetail(title);
          String result = file.getName().substring(0, file.getName().lastIndexOf("."));
          assetMediaDTO.setTitle(result);
          assetMediaDTO.setTagDTOList(createTagPostDTOList);
          GlobalVariables.assetMediaDTOList.add(assetMediaDTO);
  
      }
  
  
      /*
       * Begins to upload the file specified by the file path.
       */
      private void beginUpload1(String filePath, String pathThum) {
          Log.d("beginUpload1","method called");
          if (filePath == null) {
              Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
                      Toast.LENGTH_LONG).show();
              return;
          }
          File file = new File(filePath);
          TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
                  file,CannedAccessControlList.PublicRead);
        //  temp1=file.getName();
  
      }
  
  
      //To delete assets from list
      public void deleteMediaUpload(final int position)
      {
          final int position1=position+1;
          AlertDialog.Builder builder;
          if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) {
              builder = new AlertDialog.Builder(GlobalVariables.mActivity, android.R.style.Theme_Material_Light_Dialog_Alert);
          } else {
              builder = new AlertDialog.Builder(GlobalVariables.mActivity);
          }
          builder.setMessage("Do you want to delete this media?")
                  .setTitle("");
          builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id)
              {
                  dialog.dismiss();
                  if (position &gt;= 0 &amp;&amp; position1 &lt; observers.size())
                  {
                      try {
                          transferUtility.deleteTransferRecord(observers.get(position).getId());
                          transferUtility.deleteTransferRecord(observers.get(position1).getId());
                          observers.remove(position1);
                          transferRecordMaps.remove(position1);
                          observers.remove(position);
                          transferRecordMaps.remove(position);
                          AddMediaAssetActivity.galleryDTOArrayList1.remove(position);
                      }catch (Exception e)
                      {
  
                      }
                      updateList();
                      try {
                          GlobalVariables.assetMediaDTOList.remove(position);
                      }catch (Exception e)
                      {
  
                      }
                  }
              }
          });
          builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id)
              {
                  dialog.dismiss();
              }
          });
          AlertDialog dialog = builder.create();
          dialog.setCanceledOnTouchOutside(false);
          dialog.show();
          dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
          dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
  
      }
  
  //    /**
  //     * Gets all relevant transfers from the Transfer Service for populating the
  //     * UI
  //     */
  //    private void initData() {
  //        counter=0;
  //        failedcounter=0;
  //        navigate=0;
  //        transferRecordMaps.clear();
  //        transferRecordMaps1.clear();
  //        // Use TransferUtility to get all upload transfers.
  //        observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
  //        TransferListener listener = new UploadMediaToAssetFragment.UploadListener();
  //        for (TransferObserver observer : observers) {
  //
  //            // For each transfer we will will create an entry in
  //            // transferRecordMaps which will display
  //            // as a single row in the UI
  //            HashMap&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
  //            Util.fillMap(map, observer, false);
  //
  //            transferRecordMaps.add(map);
  //
  //            // Sets listeners to in progress transfers
  //            if (TransferState.WAITING.equals(observer.getState())
  //                    || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
  //                    || TransferState.IN_PROGRESS.equals(observer.getState())) {
  //                observer.setTransferListener(listener);
  //            }
  //        }
  //        transferRecordMaps1.clear();
  //        for(int i=0;i&lt;transferRecordMaps.size();i++)
  //        {
  //            File file = new File((String) transferRecordMaps.get(i).get("fileName"));
  //            if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
  //            {
  //            }
  //            else
  //            {
  //                transferRecordMaps1.add(transferRecordMaps.get(i));
  //
  //            }
  //
  //        }
  //        assetListAdapter.notifyDataSetChanged();
  //    }
  
      /*
       * A TransferListener class that can listen to a upload task and be notified
       * when the status changes.
       */
      public class UploadListener implements TransferListener {
  
          // Simply updates the UI list when notified.
          @Override
          public void onError(int id, Exception e)
          {
              failedcounter++;
              updateList();
  
          }
  
          @Override
          public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
  
              updateList();
  
              currentbyte =bytesCurrent;
              totalbyte =bytesTotal;
              Log.d("onprogresschnaged","method bytes"+bytesCurrent+" bytestotoal"+bytesTotal);
          }
  
          @Override
          public void onStateChanged(int id, TransferState newState)
          {
              if (newState.equals(TransferState.COMPLETED))
              {
                  counter++;
                  updateList();
              } else if (newState.equals(TransferState.FAILED))
              {
                  failedcounter++;
                 updateList();
              }
  
  
  
  
          }
  
      }
      /*
       * Updates the ListView according to the observers.
       */
      /*
       * Updates the ListView according to the observers.
       */
      public void updateList()
      {
          if(transferRecordMaps!=null&amp;&amp;transferRecordMaps.size()&gt;0)
          {
              TransferObserver observer = null;
              HashMap&lt;String, Object&gt; map = null;
              for (int i = 0; i &lt; observers.size(); i++) {
                  observer = observers.get(i);
                  map = transferRecordMaps.get(i);
                   progress = (int) ((double) observer.getBytesTransferred() * 100 / observer
                          .getBytesTotal());
  
                  Log.d("progressuploadingData"," map"+progress);
  
                  Util.fillMap(map, observer, i == checkedIndex);
                  Log.d("uploadingData"," map"+map+" observer"+observer);
  
              }
              transferRecordMaps1.clear();
              for (int i = 0; i &lt; transferRecordMaps.size(); i++)
              {
                  File file = new File((String) transferRecordMaps.get(i).get("fileName"));
                  if (file.getName().substring(0, 2).equalsIgnoreCase("0!")) {
                  } else
                  {
                      transferRecordMaps1.add(transferRecordMaps.get(i));
  
                  }
                  totalcount=transferRecordMaps.size();
                  totalAssetCount=counter+failedcounter;
                  Log.d("totalcount","count"+totalcount+"toatlassetcount"+totalAssetCount);
                  if(counter&gt;1&amp;&amp;totalAssetCount&gt;=totalcount&amp;&amp;GlobalVariables.assetMediaDTOList.size()&gt;0)
                  {
                      Log.d("myservice asset","complete");
                      navigate=1;
  
                      Intent intent = new Intent(this, DialogeActivity.class);
                      context.getApplicationContext().startActivity(intent);
  
                     // Toast.makeText(this,"Your asset uploaded successfully",Toast.LENGTH_LONG).show();
  //                    Intent notificationIntent = new Intent(this, DialogeActivity.class);
  //                    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
  //                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
  //                            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  //                    startActivity(notificationIntent);
  
  
  //                    Notification notification = new NotificationCompat.Builder(this)
  //                            .setContentTitle("Visibly")
  //                            .setTicker("asset uploaded")
  //                            .setContentText("asset uploaded successfully")
  //                            .setSmallIcon(R.drawable.ic_launcher)
  //                            .build();
  
  
  
  
  
  //                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
  //                    builder.setTitle("Test dialog");
  //                    builder.setIcon(R.drawable.icon);
  //                    builder.setMessage("Content");
  //                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  //                        public void onClick(DialogInterface dialog, int whichButton) {
  //                            //Do something
  //                            dialog.dismiss();
  //                        });
  //
  //                        AlertDialog alert = builder.create();
  //            alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
  //                alert.show();
  
  //                    AlertDialog alertDialog = new AlertDialog.Builder(this)
  //                            .setTitle("Title")
  //                            .setMessage("Are you sure?")
  //                            .create();
  //
  //                    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
  //                    alertDialog.show();
  //                    button_Done.setVisibility(View.VISIBLE);
  //                    button_Done.setText("Done");
  //                    button_Done.setEnabled(true);
  //                    button_Done.setClickable(true);
  
                  }else if(failedcounter&gt;=totalcount)
                  {
                      navigate=0;
  //                    button_Done.setVisibility(View.VISIBLE);
  //                    button_Done.setText("Back");
  //                    button_Done.setEnabled(true);
  //                    button_Done.setClickable(true);
                  }else
                  {
  //                    button_Done.setVisibility(View.VISIBLE);
  //                    button_Done.setText("Please wait.");
  //                    button_Done.setEnabled(false);
  //                    button_Done.setClickable(false);
                  }
              }
  
  
             // assetListAdapter.notifyDataSetChanged();
          }else
          {
  //            Intent intent=null;
  //            if( AssetFolderActivity.folderDTO!=null&amp;&amp;AssetFolderActivity.folderDTO.getFolderIdentity()!=null&amp;&amp; AssetFolderActivity.folderDTO.getFolderIdentity().length()&gt;0&amp;&amp;!AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("")) {
  //                intent = new Intent(activity, AssetFolderActivity.class);
  //            }else
  //            {
  //                intent = new Intent(activity, DashboardActivity.class);
  //            }
  //            intent.putExtra("folderDTO", AssetFolderActivity.folderDTO);
  //            activity.startActivity(intent);
  //            activity.finish();
          }
  
      }
  
      private void initData() {
          counter=0;
          failedcounter=0;
          navigate=0;
          transferRecordMaps.clear();
          transferRecordMaps1.clear();
          // Use TransferUtility to get all upload transfers.
          observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
          TransferListener listener =  new ForegroundService().new UploadListener();
          for (TransferObserver observer : observers) {
  
              // For each transfer we will will create an entry in
              // transferRecordMaps which will display
              // as a single row in the UI
              HashMap&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
              Util.fillMap(map, observer, false);
  
              transferRecordMaps.add(map);
  
              // Sets listeners to in progress transfers
              if (TransferState.WAITING.equals(observer.getState())
                      || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
                      || TransferState.IN_PROGRESS.equals(observer.getState())) {
                  observer.setTransferListener(listener);
              }
          }
          transferRecordMaps1.clear();
          for(int i=0;i&lt;transferRecordMaps.size();i++)
          {
              File file = new File((String) transferRecordMaps.get(i).get("fileName"));
              if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
              {
              }
              else
              {
                  transferRecordMaps1.add(transferRecordMaps.get(i));
              }
  
          }
         // assetListAdapter.notifyDataSetChanged();
      }
  
  }
  </code></pre>