extends Service : Service « Network « Android






extends Service

  
package app.test;

import java.io.File;
import java.util.Date;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

class CompassView extends View {
  private Paint markerPaint;
  private Paint textPaint;
  private Paint circlePaint;
  private String northString;
  private String eastString;
  private String southString;
  private String westString;
  private int textHeight;
  private float bearing;
  public void setBearing(float _bearing) {
    bearing = _bearing;
  }
  public float getBearing() {
    return bearing;
  }
  public CompassView(Context context) {
    super(context);
    initCompassView();
  }
  public CompassView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initCompassView();
  }
  public CompassView(Context context, AttributeSet attrs, int defaultStyle) {
    super(context, attrs, defaultStyle);
    initCompassView();
  }
  protected void initCompassView() {
    setFocusable(true);
    circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    circlePaint.setColor(Color.CYAN);
    circlePaint.setStrokeWidth(1);
    circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
    Resources r = this.getResources();
    northString = "N";
    eastString = "E";
    southString = "S";
    westString = "W";

    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(Color.BLACK);

    textHeight = (int) textPaint.measureText("yY");

    markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    markerPaint.setColor(Color.BLUE);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int measuredWidth = measure(widthMeasureSpec);
    int measuredHeight = measure(heightMeasureSpec);
    int d = Math.min(measuredWidth, measuredHeight);
    setMeasuredDimension(d, d);
  }

  private int measure(int measureSpec) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    if (specMode == MeasureSpec.UNSPECIFIED) {
      result = 200;
    } else {
      result = specSize;
    }
    return result;
  }

  @Override
  protected void onDraw(Canvas canvas) {
    int px = getMeasuredWidth() / 2;
    int py = getMeasuredHeight() / 2;

    int radius = Math.min(px, py);
    canvas.drawCircle(px, py, radius, circlePaint);
    canvas.save();
    canvas.rotate(-bearing, px, py);
    int textWidth = (int) textPaint.measureText("W");
    int cardinalX = px - textWidth / 2;
    int cardinalY = py - radius + textHeight;

    for (int i = 0; i < 24; i++) {
      canvas.drawLine(px, py - radius, px, py - radius + 10, markerPaint);
      canvas.save();
      canvas.translate(0, textHeight);
      if (i % 6 == 0) {
        String dirString = "";
        switch (i) {
        case (0): {
          dirString = northString;
          int arrowY = 2 * textHeight;
          canvas.drawLine(px, arrowY, px - 5, 3 * textHeight,
              markerPaint);
          canvas.drawLine(px, arrowY, px + 5, 3 * textHeight,
              markerPaint);
          break;
        }
        case (6):
          dirString = eastString;
          break;
        case (12):
          dirString = southString;
          break;
        case (18):
          dirString = westString;
          break;
        }
        canvas.drawText(dirString, cardinalX, cardinalY, textPaint);
      } else if (i % 3 == 0) {
        String angle = String.valueOf(i * 15);
        float angleTextWidth = textPaint.measureText(angle);

        int angleTextX = (int) (px - angleTextWidth / 2);
        int angleTextY = py - radius + textHeight;
        canvas.drawText(angle, angleTextX, angleTextY, textPaint);
      }
      canvas.restore();

      canvas.rotate(15, px, py);
    }
    canvas.restore();
  }
}

class MyService extends Service {

  @Override
  public void onCreate() {
  }

  @Override
  public void onStart(Intent intent, int startId) {
  }

  @Override
  public IBinder onBind(Intent intent) {
    return binder;
  }

  private final IBinder binder = new MyBinder();

  public class MyBinder extends Binder {
    MyService getService() {
      return MyService.this;
    }
  }
}

public class Test extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Intent bindIntent = new Intent(Test.this, MyService.class);
    bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);

    startMyService();
    runBackgroundTask();
    showToast();
    showViewToast();
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    Context context = getApplicationContext();
    int icon = R.drawable.icon;
    String tickerText = "Notification";
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, tickerText, when);
    String expandedText = "Extended status text";
    String expandedTitle = "Notification Title";
    Intent intent = new Intent(this, Test.class);
    PendingIntent launchIntent = PendingIntent.getActivity(context, 0,
        intent, 0);
    notification.setLatestEventInfo(context, expandedTitle, expandedText,
        launchIntent);
    int notificationRef = 1;
    notification.number++;
    notificationManager.notify(notificationRef, notification);
    notification.number = 10;
    notificationManager.notify(notificationRef, notification);
    Uri ringURI = Uri.fromFile(new File(
        "/system/media/audio/ringtones/ringer.mp3"));
    notification.sound = ringURI;
    long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 };
    notification.vibrate = vibrate;
    notification.ledARGB = Color.RED;
    notification.ledOffMS = 0;
    notification.ledOnMS = 1;
    notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;
    notification.flags = notification.flags
        | Notification.FLAG_ONGOING_EVENT;
    notification.flags = notification.flags | Notification.FLAG_INSISTENT;
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    String MY_RTC_ALARM = "MY_RTC_ALARM";
    String ALARM_ACTION = "ALARM_ACTION";

    int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
    long timeOrLengthofWait = 10000;
    Intent intentToFire = new Intent(ALARM_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
        intentToFire, 0);
    alarms.set(alarmType, timeOrLengthofWait, pendingIntent);

    PendingIntent rtcIntent = PendingIntent.getBroadcast(this, 0,
        new Intent(MY_RTC_ALARM), 1);
    PendingIntent elapsedIntent = PendingIntent.getBroadcast(this, 0,
        new Intent(ALARM_ACTION), 1);
    Date t = new Date();
    t.setTime(java.lang.System.currentTimeMillis() + 60 * 1000 * 5);
    alarms.set(AlarmManager.RTC_WAKEUP, t.getTime(), rtcIntent);
    alarms.set(AlarmManager.ELAPSED_REALTIME, 30 * 60 * 1000, elapsedIntent);
    alarms.cancel(rtcIntent);
  }

  private void showToast() {
    Context context = getApplicationContext();
    String msg = "Displaying a Toast!";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, msg, duration);
    toast.setGravity(Gravity.BOTTOM, 0, 0);
    toast.show();
  }

  private void showViewToast() {
    Context context = getApplicationContext();
    String msg = "Displaying a Toast!";
    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, msg, duration);
    int offsetX = 0;
    int offsetY = 0;
    toast.setGravity(Gravity.TOP, offsetX, offsetY);

    LinearLayout ll = new LinearLayout(context);
    ll.setOrientation(LinearLayout.VERTICAL);

    TextView myTextView = new TextView(context);
    CompassView cv = new CompassView(context);

    myTextView.setText(msg);

    int lHeight = LinearLayout.LayoutParams.FILL_PARENT;
    int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;

    ll.addView(cv, new LinearLayout.LayoutParams(lHeight, lWidth));
    ll.addView(myTextView, new LinearLayout.LayoutParams(lHeight, lWidth));

    ll.setPadding(40, 50, 0, 50);

    toast.setView(ll);
    toast.show();
  }

  private MyService serviceBinder;
  private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
      serviceBinder = ((MyService.MyBinder) service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
      serviceBinder = null;
    }
  };

  private void startMyService() {
    ComponentName service = startService(new Intent(this, MyService.class));
    stopService(new Intent(this, service.getClass()));
    try {
      Class serviceClass = Class.forName(service.getClassName());
      stopService(new Intent(this, serviceClass));
    } catch (ClassNotFoundException e) {
    }
  }

  private Handler handler = new Handler();

  private void runBackgroundTask() {
    mainProcessing();
  }

  private void mainProcessing() {
    Thread thread = new Thread(null, doBackgroundThreadProcessing,
        "Background");
    thread.start();
  }
  private Runnable doBackgroundThreadProcessing = new Runnable() {
    public void run() {
      backgroundThreadProcessing();
    }
  };
  private void backgroundThreadProcessing() {
    handler.post(doUpdateGUI);
  }
  private Runnable doUpdateGUI = new Runnable() {
    public void run() {
      Context context = getApplicationContext();
      String msg = "Displaying a Toast!";
      int duration = Toast.LENGTH_SHORT;
      Toast.makeText(context, msg, duration).show();
    }
  };
}

   
    
  








Related examples in the same category

1.Map Service
2.Widget Service
3.Restful web service task
4.Search with Restful service
5.Post Restful service
6.Tracker Service
7.Weather web service
8.Access a Web service using GET
9.Alarm service
10.Get Running Services Info
11.Local service demo
12.Service structure
13.Clock Back Service
14.Voice Recognition Service
15.is Connected by Context.CONNECTIVITY_SERVICE
16.BeatService extends Service and Thread
17.TimeoutService (beta). Here you can register a timeout.
18.Timeout Service
19.Screenshot Service