[Android]PackageManagerでアクティビティの有効無効を動的に切り替える

PackageManagerでアクティビティの有効無効を動的に切り替える方法のメモ

package com.foobar;

import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestActivity extends Activity {

  Button btn;
  boolean isSubActivityEnable;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_test);

    btn = (Button) findViewById(R.id.button1);
    PackageManager pm = getPackageManager();
    ComponentName cn = new ComponentName(this, SubActivity.class);

    isSubActivityEnable = pm.getComponentEnabledSetting(cn) ==
      PackageManager.COMPONENT_ENABLED_STATE_ENABLED;

    setButtonText();

    btn.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
        if( isSubActivityEnable){
          pm.setComponentEnabledSetting(cn,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
        }else {
          pm.setComponentEnabledSetting(cn,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
        }
        isSubActivityEnable = !isSubActivityEnable;
        setButtonText();
      }
    });
  }

  void setButtonText() {
    if (isSubActivityEnable) {
      btn.setText("Disable SubActivity");
    } else {
      btn.setText("Enable SubActivity");
    }
  }
}
Share