Skip to content

Instantly share code, notes, and snippets.

@jmatsu
Created April 8, 2015 14:28
Show Gist options
  • Save jmatsu/771d71f12462198b1a30 to your computer and use it in GitHub Desktop.
Save jmatsu/771d71f12462198b1a30 to your computer and use it in GitHub Desktop.
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.view.View;
/*
* Copyright {2014} {Matsuda Jumpei}
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* @author jmatsu
*
*/
public class CommonUtil {
private static final String TAG = CommonUtil.class.getSimpleName();
private CommonUtil() {
}
/**
* Checking the status of the specific service
* @param act
* @param serviceClass
* @return Returns true if the service is running, otherwise false.
*/
public static boolean isServiceRunning(Activity act,
Class<? extends Service> serviceClass) {
ActivityManager manager = (ActivityManager) act
.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo rsinfo : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(rsinfo.service.getClassName())) {
return true;
}
}
return false;
}
/**
* Starting the service if it's not running.
* @param act
* @param serviceClass
*/
public static void startService(Activity act,
Class<? extends Service> serviceClass) {
if (!isServiceRunning(act, serviceClass)) {
Log.d(TAG, serviceClass.getName() + " is not running. Awake it.");
act.startService(new Intent(act, serviceClass));
} else {
Log.d(TAG, serviceClass.getName() + " is running");
}
}
/**
* Stopping the service if it's running.
* @param act
* @param serviceClass
*/
public static void stopService(Activity act,
Class<? extends Service> serviceClass) {
if (isServiceRunning(act, serviceClass)) {
Log.i(TAG, serviceClass.getName() + " is running. KILL it.");
act.stopService(new Intent(act, serviceClass));
} else {
Log.i(TAG, serviceClass.getName() + " is not running");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment