启动我的应用程序按音量键应用程序关闭时按下

时间:2018-04-20 07:08:53

标签: android

当我退出我的应用程序时,我想点击音量按钮再次启动它而不点击应用程序的图标。因为我将隐藏图标,只通过音量按钮启动应用程序,这是代码和谢谢。

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //////// this to hide the app icon  ///////////////

    PackageManager p = getPackageManager();
    ComponentName componentName = new ComponentName(this, com.test.MainActivity.class);
    p.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

  }


   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == android.view.KeyEvent.KEYCODE_VOLUME_DOWN)) {

      //Do something  
      Toast.makeText(MainActivity.this, "Down working", Toast.LENGTH_SHORT).show();

    }
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

您应该使用广播接收器按音量按钮。

在清单文件中注册接收器

<receiver android:name="com.package.CallBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.media.VOLUME_CHANGED_ACTION" />
    </intent-filter>
</receiver>

并且您的广播活动看起来像这样

public class CallBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {     
        Intent i = new Intent();
        i.setClassName("com.package", "com.package.MainActivity");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);      
    }
}