Tuesday, August 19, 2014

Android Slack send message example (Incoming WebHooks)

In slack, click "Configure Intergrations" and "Incoming WebHooks"
Create your application and "Incoming WebHooks" url with token.


Put "getInstance()"




/*
 * Made by ShakeJ (shakejj@gmail.com). Send message to slack's channel. Use
 * 'Incoming WebHooks' http://mnworld.co.kr Search 'ShakeJ' in google play :)
 */

public class SlackMessageUtil
{
  protected String siteUrl;
  private volatile static SlackMessageUtil uniqueInstance;
  
  
  private SlackMessageUtil(String incomingWebHookUrl)
  {
    this.siteUrl = incomingWebHookUrl;
  }
  
  
  public static SlackMessageUtil getInstance(Context context, String incomingWebHookUrl)
  {
    if (uniqueInstance == null)
      synchronized (SlackMessageUtil.class)
      {
        if (uniqueInstance == null)
          uniqueInstance = new SlackMessageUtil(incomingWebHookUrl);
      }
    return uniqueInstance;
  }
  
  
  @SuppressWarnings("unchecked")
  public void sendMessage(String channel, String message, String name)
  {
    JSONObject obj = new JSONObject();
    
    try
    {
      obj.put("channel", channel);
      obj.put("username", name);
      obj.put("text", message);
    }
    catch (JSONException e)
    {
      e.printStackTrace();
    }
    
    List params = new ArrayList();
    params.add(new BasicNameValuePair("payload", obj.toString()));
    new RequestAsyncTask().execute(params);
  }
  
  private class RequestAsyncTask extends AsyncTask, Integer, Boolean>
  {
    @Override
    protected Boolean doInBackground(List... params)
    {
      boolean result = false;
      try
      {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpRequestBase requestBase = null;
        
        requestBase = new HttpPost(siteUrl);
        ((HttpPost) requestBase).setHeader("Content-Type", "application/x-www-form-urlencoded");
        ((HttpPost) requestBase).setEntity(new UrlEncodedFormEntity(params[0], "UTF-8"));
        HttpResponse response = client.execute(requestBase);
        
        if (response.getStatusLine().getStatusCode() < 400)
          result = true;
        else
          result = false;
        
        Log.w("WARN", "Send message to slack result : " + result);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
      return result;
    }
  }
  
}

No comments:

Post a Comment

I Love Your Message^.^
Have a Nice day!