Android Open Source - Common-Library Custom Service






From Project

Back to project page Common-Library.

License

The source code is released under:

Apache License

If you think the Android project Common-Library listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.morgan.library.snippet;
//from w w w  . j  a v  a  2  s  . c o  m
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.morgan.library.R;
import com.morgan.library.utils.Logger;

/**
 * ??????Service???????????????????Service??????????Notification
 * 
 * @author Morgan.Ji
 * 
 */
public class CustomService extends Service {

  private static final String TAG = CustomService.class.getName();

  private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
  private static final Class<?>[] mStartForegroundSignature = new Class[] {
      int.class, Notification.class };
  private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };

  private NotificationManager mNM;
  private Method mSetForeground;
  private Method mStartForeground;
  private Method mStopForeground;
  private Object[] mSetForegroundArgs = new Object[1];
  private Object[] mStartForegroundArgs = new Object[2];
  private Object[] mStopForegroundArgs = new Object[1];

  public static final int mNotificationId = 0x0002;
  private static final String PACKAGE = "";
  private static final String LAUNCHCLASS = "";

  private void invokeMethod(Method method, Object[] args) {
    try {
      method.invoke(this, args);
    } catch (InvocationTargetException e) {
      // Should not happen.
      Logger.e(TAG, "Unable to invoke method", e);
    } catch (IllegalAccessException e) {
      // Should not happen.
      Logger.e(TAG, "Unable to invoke method", e);
    }
  }

  /**
   * This is a wrapper around the new startForeground method, using the older
   * APIs if it is not available.
   */
  private void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
      mStartForegroundArgs[0] = Integer.valueOf(id);
      mStartForegroundArgs[1] = notification;
      invokeMethod(mStartForeground, mStartForegroundArgs);
    } else {
      // Fall back on the old API.
      mSetForegroundArgs[0] = Boolean.TRUE;
      invokeMethod(mSetForeground, mSetForegroundArgs);
      mNM.notify(id, notification);
    }

  }

  private Notification createNotification() {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
        this).setSmallIcon(R.drawable.icon_launcher)
        .setContentTitle(getString(R.string.app_name))
        .setContentText(getResources().getString(R.string.app_name));
    mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    mBuilder.setAutoCancel(false);

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setComponent(new ComponentName(PACKAGE, LAUNCHCLASS));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        intent, 0);

    mBuilder.setContentIntent(contentIntent);

    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification notification = mBuilder.build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.contentIntent = contentIntent;
    return notification;
  }

  /**
   * This is a wrapper around the new stopForeground method, using the older
   * APIs if it is not available.
   */
  private void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
      mStopForegroundArgs[0] = Boolean.TRUE;
      invokeMethod(mStopForeground, mStopForegroundArgs);
    } else {
      // Fall back on the old API. Note to cancel BEFORE changing the
      // foreground state, since we could be killed at that point.
      mNM.cancel(id);
      mSetForegroundArgs[0] = Boolean.FALSE;
      invokeMethod(mSetForeground, mSetForegroundArgs);
    }

  }

  @Override
  public void onCreate() {
    initForegroundCompat();
    startForegroundCompat(mNotificationId, createNotification());
  }

  private void initForegroundCompat() {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    try {
      mStartForeground = getClass().getMethod("startForeground",
          mStartForegroundSignature);
      mStopForeground = getClass().getMethod("stopForeground",
          mStopForegroundSignature);
      return;
    } catch (NoSuchMethodException e) {
      // Running on an older platform.
      mStartForeground = mStopForeground = null;
    }
    try {
      mSetForeground = getClass().getMethod("setForeground",
          mSetForegroundSignature);
    } catch (NoSuchMethodException e) {
      throw new IllegalStateException(
          "OS doesn't have Service.startForeground OR Service.setForeground!");
    }
  }

  @Override
  public void onDestroy() {
    // Make sure our notification is gone.
    stopForegroundCompat(mNotificationId);
  }

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




Java Source Code List

com.morgan.library.app.APPContext.java
com.morgan.library.app.AppManager.java
com.morgan.library.app.BaseActivity.java
com.morgan.library.app.BaseFragmentActivity.java
com.morgan.library.app.BaseListActivity.java
com.morgan.library.app.BaseScreenShotActivity.java
com.morgan.library.app.CommonApplication.java
com.morgan.library.async.CustomAsyncTask.java
com.morgan.library.async.Destroyable.java
com.morgan.library.async.IFeedback.java
com.morgan.library.async.TaskManager.java
com.morgan.library.model.NetResult.java
com.morgan.library.model.SpinnerItem.java
com.morgan.library.model.WeatherType.java
com.morgan.library.model.Weather.java
com.morgan.library.net.ApiClient.java
com.morgan.library.net.ApiManager.java
com.morgan.library.net.ApiUrl.java
com.morgan.library.net.IApiClient.java
com.morgan.library.net.JsonUtils.java
com.morgan.library.net.MockApiClient.java
com.morgan.library.service.LocationManager.java
com.morgan.library.service.WeatherManager.java
com.morgan.library.snippet.CookieShare.java
com.morgan.library.snippet.CustomService.java
com.morgan.library.snippet.ExceptionCatcher.java
com.morgan.library.snippet.ProxyUsage.java
com.morgan.library.snippet.SocketClient.java
com.morgan.library.snippet.SocketServer.java
com.morgan.library.snippet.UDPClient.java
com.morgan.library.snippet.UDPServer.java
com.morgan.library.snippet.XMLAnalyze.java
com.morgan.library.task.GetWeatherTask.java
com.morgan.library.utils.AppUtils.java
com.morgan.library.utils.DateUtils.java
com.morgan.library.utils.DensityUtils.java
com.morgan.library.utils.FileUtils.java
com.morgan.library.utils.GB2Alpha.java
com.morgan.library.utils.HttpClientUtil.java
com.morgan.library.utils.HttpClientUtils.java
com.morgan.library.utils.HttpURLUtil.java
com.morgan.library.utils.ImageUtils.java
com.morgan.library.utils.KeyBoardUtils.java
com.morgan.library.utils.LocationUtils.java
com.morgan.library.utils.Logger.java
com.morgan.library.utils.NetUtils.java
com.morgan.library.utils.PhoneUtils.java
com.morgan.library.utils.SDCardUtils.java
com.morgan.library.utils.StrUtils.java
com.morgan.library.widget.AutoHideMenuWidget.java
com.morgan.library.widget.BadgeView.java
com.morgan.library.widget.CityPickerWidget.java
com.morgan.library.widget.CustomGridView.java
com.morgan.library.widget.CustomListView.java
com.morgan.library.widget.CustomToast.java
com.morgan.library.widget.CustomViewPager.java
com.morgan.library.widget.DatePickerWidget.java
com.morgan.library.widget.DirectionScrollView.java
com.morgan.library.widget.FallBallView.java
com.morgan.library.widget.HeightPickerWidget.java
com.morgan.library.widget.InterceptPressLayout.java
com.morgan.library.widget.ItalicTextView.java
com.morgan.library.widget.PopupMenuWidget.java
com.morgan.library.widget.PullToRefreshListView.java
com.morgan.library.widget.ScreenShotView.java
com.morgan.library.widget.SexPickerWidget.java
com.morgan.library.widget.SlideUpOpenWidget.java
com.morgan.library.widget.SwipeListView.java
com.morgan.library.widget.TimePickerWidget.java
com.morgan.library.widget.TouchZoomImageView.java
com.morgan.library.widget.WaitScreenWidget.java
com.morgan.library.widget.WebViewDialog.java
com.morgan.library.widget.WeightPickerWidget.java
com.morgan.library.widget.calendar.CalendarGridView.java
com.morgan.library.widget.calendar.CalendarScrollView.java
com.morgan.library.widget.calendar.CalendarViewFlipper.java
com.morgan.library.widget.calendar.CalendarWidget.java
com.morgan.library.widget.numberpicker.NumberPicker.java
com.morgan.library.widget.numberpicker.Scroller.java
com.morgan.library.widget.slidemenu.ScrollDetectorFactory.java
com.morgan.library.widget.slidemenu.ScrollDetectors.java
com.morgan.library.widget.slidemenu.SlideMenu.java