2013-07-01 93 views

回答

13

通過使用您可以啓用包管理器或menifest文件 宣佈禁止部分有兩個標誌PackageManager.COMPONENT_ENABLED_STATE_DISABLED的禁用成分,PackageManager.COMPONENT_ENABLED_STATE_ENABLED爲啓用組件。

PackageManager pm = getApplicationContext().getPackageManager(); 
    ComponentName componentName = new ComponentName("com.app", 
     ".broadcast_receivers.OnNetworkChangedReceiver"); 
     pm.setComponentEnabledSetting(componentName, 
     PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
     PackageManager.DONT_KILL_APP); 

Android清單:

<receiver android:name=".broadcast_receivers.OnNetworkChangedReceiver" 
      android:enabled="true"> 
     <intent-filter> 
       <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> 
     </intent-filter> 
</receiver> 
+1

相同的代碼都啓用和禁用成分還是有細微的差別? – scibor

+0

沒關係,你回答了它,謝謝 – scibor

+0

禁用組件PackageManager.COMPONENT_ENABLED_STATE_DISABLED 和啓用組件PackageManager.COMPONENT_ENABLED_STATE_ENABLED –

0

採取爬完方法更通用的實現:

public static void setComponentState(Context context, String packageName , String componentClassName, boolean enabled) 
{ 
    PackageManager pm = context.getApplicationContext().getPackageManager(); 
    ComponentName componentName = new ComponentName(packageName, componentClassName); 
    int state = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 
    pm.setComponentEnabledSetting(componentName, 
      state, 
      PackageManager.DONT_KILL_APP); 

}