/* 
 * Copyright 2012 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.util;

import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

public class PackageManagerHelper
{
	public static void setEnableReceiver(Context context, Class<?> receiver,
			boolean enable) throws NameNotFoundException
	{
		ComponentName componentName = new ComponentName(context, receiver);
		int requestedSate = (enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
				PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
		PackageManager packageManager = context.getPackageManager();

		int enabledState = packageManager.getComponentEnabledSetting(componentName);
		if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
		{
			ActivityInfo info = packageManager.getReceiverInfo(componentName,
					PackageManager.GET_META_DATA |
					PackageManager.GET_DISABLED_COMPONENTS);
			enabledState = (info.enabled) ?
					PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
					PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
		}
		
		if (enabledState != requestedSate)
			packageManager.setComponentEnabledSetting(componentName, requestedSate,
					PackageManager.DONT_KILL_APP);
	}
}
