Raw service with bindings

public class Request2Service extends Service {

    public static final int MSG_REGISTER_WATCHER = -1;
    public static final int MSG_UNREGISTER_WATCHER = -2;

    private ArrayList<Messenger> clients = new ArrayList<>();

    private Messenger clientMessenger = new Messenger(new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REGISTER_WATCHER:
                    if (!clients.contains(msg.replyTo)) {
                        clients.add(msg.replyTo);
                    }
                    break;

                case MSG_UNREGISTER_WATCHER:
                    if (clients.contains(msg.replyTo)) {
                        clients.remove(msg.replyTo);
                    }
                    break;

                // TODO: 2017-07-12 case: ... 
            }
        }
    });

    private ExecutorService executor = Executors.newCachedThreadPool();

    private static void sendToClients(ArrayList<Messenger> clients, Message msg) {

        for (int i = clients.size() - 1; i >= 0; i--) {
            try {
                Message msg2 = Message.obtain();
                msg2.what = msg.what;
                msg2.arg1 = msg.arg1;
                msg2.arg2 = msg.arg2;
                msg2.setData(msg.getData());
                msg2.replyTo = msg.replyTo;
                clients.get(i).send(msg2);
            } catch (RemoteException e) {
                clients.remove(i);
            }
        }
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, final int startId) {
        if (intent != null && intent.getAction() != null) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    handleStartCommand(intent);
                }
            });
        }
        return START_STICKY;
    }

    private void handleStartCommand(Intent intent) {
        // TODO: 2017-07-12  
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return clientMessenger.getBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

 

TIL: difference between service vs/and intentService

Source: http://stackoverflow.com/questions/15524280/service-vs-intentservice

Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.

When to use?

  • The Service can be used in tasks with no UI, but shouldn’t be too long. If you need to perform long tasks, you must use threads within Service.
  • The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

How to trigger?

  • The Service is triggered by calling method startService().
  • The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

Triggered From

  • The Service and IntentService may be triggered from any thread, activity or other application component.

Runs On

  • The Service runs in background but it runs on the Main Thread of the application.
  • The IntentService runs on a separate worker thread.

Limitations / Drawbacks

  • The Service may block the Main Thread of the application.
  • The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.

When to stop?

  • If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don’t need to implement this method).
  • The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().

Working example POST in android

Here is another short (IMHO) example how to post in android app.

private void postSms(String text) {
URL url;
HttpURLConnection urlConnection = null;

try {
url = new URL("http://yourserver.com/sendsms");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sms", text));//POST param as "sms"

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

String status = new String(Streams.getBytes(urlConnection.getInputStream()));
Log.d(TAG, new Exception().getStackTrace()[0].getMethodName() + ":insert status=" + status);

} catch (MalformedURLException | ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

This is a method for concatenating parameters for POST

Continue reading “Working example POST in android”