Page 1 of 1

A simple Service and client

Posted: Thu Oct 03, 2013 6:05 pm
by fabiodelorenzo
The service starter:

Code: Select all

package info.delorenzo.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServiceTestActivity extends Activity implements OnClickListener {
   
   private static String TAG="ServiceTestActivity";
   private Intent serviceIntent;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d(TAG, "onCreate");
       
      Button startButton = (Button) (findViewById(R.id.buttonstart));
      Button stopButton = (Button) (findViewById(R.id.buttonstop));
      startButton.setOnClickListener(this);
      stopButton.setOnClickListener(this);
      serviceIntent = new Intent(this,MyService.class);
    }
   
   
    private void startMyService() {
       serviceIntent.putExtra("passedData", "ciao");
       Log.d(TAG, "startMyService going to call startService");
       startService(serviceIntent);
    }
    private void stopMyService() {       
       Log.d(TAG, "stopMyService going to call stopService");
       stopService(serviceIntent);
    }

   @Override
   public void onClick(View v) {
      // TODO Auto-generated method stub     
      if (v.getId() == R.id.buttonstart) {
         Log.d(TAG,"Button Start Pressed");
         startMyService();
      }         
      else if (v.getId() == R.id.buttonstop) {
         Log.d(TAG,"Button Stop Pressed");
         stopMyService();
      }
      else Log.d(TAG,"unknown Button pressed");
     
   }
}


The service:

Code: Select all

package info.delorenzo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

   private static String TAG="MyService";

   @Override
   public void onCreate() {
      Log.d(TAG,"onCreate");
   }

   @Override
   public IBinder onBind(Intent intent) {
      Log.d(TAG,"onBind");
      return null;
   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      Log.d(TAG, "onStartCommand Received start id " + startId + ": " + intent);
      Bundle extraData = intent.getExtras();
      if (extraData != null) {         
         Log.d(TAG, "onStartCommand extra data=" + extraData.getString("passedData") );         
      }
      else
         Log.d(TAG, "onStartCommand no additional extra data");
     
     
      // We want this service to continue running until it is explicitly
      // stopped, so return sticky.
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      Log.d(TAG,"onDestroy");
   }

}