Skip to content

Instantly share code, notes, and snippets.

@kraxarn
Last active March 30, 2023 06:49
Show Gist options
  • Save kraxarn/48dd10359d3ecf05d599638d9799eb43 to your computer and use it in GitHub Desktop.
Save kraxarn/48dd10359d3ecf05d599638d9799eb43 to your computer and use it in GitHub Desktop.
Quick Sound Toggle Source Code
package com.crow.sound_quick_toggle;
/*
Version 1.0
By kraxarn
Licensed under WTFPL
*/
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.media.AudioManager;
import android.provider.Settings;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import android.widget.Toast;
public class QuickSoundTile extends TileService
{
private enum RingerMode
{
Silent,
Vibrate,
Normal
}
private AudioManager audioManager;
private NotificationManager notificationManager;
private AudioManager getAudioManager()
{
if (audioManager == null)
audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
return audioManager;
}
private NotificationManager getNotificationManager()
{
if (notificationManager == null)
notificationManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
return notificationManager;
}
private RingerMode getRingerMode()
{
return RingerMode.values()[getAudioManager().getRingerMode()];
}
private void setRingerMode(RingerMode mode)
{
// Check permissions
if (!getNotificationManager().isNotificationPolicyAccessGranted())
{
Toast.makeText(getApplicationContext(), "Please grant notification access first", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
return;
}
getAudioManager().setRingerMode(mode.ordinal());
updateTileStyle();
}
// Update tile icon and label
private void updateTileStyle()
{
Tile tile = getQsTile();
RingerMode ringerMode = getRingerMode();
tile.setIcon(getIcon(ringerMode));
tile.setLabel(ringerMode.name());
tile.updateTile();
}
private Icon getIcon(RingerMode mode)
{
return Icon.createWithResource(getApplicationContext(), getIconResource(mode));
}
private int getIconResource(RingerMode mode)
{
switch (mode)
{
case Silent:
return R.drawable.ic_bell_off_outline;
case Vibrate:
return R.drawable.ic_vibrate;
case Normal:
return R.drawable.ic_bell_outline;
}
return R.drawable.ic_bell_outline;
}
@Override
public void onTileAdded()
{
super.onTileAdded();
updateTileStyle();
}
@Override
public void onClick()
{
super.onClick();
RingerMode newMode = RingerMode.values()[(getRingerMode().ordinal() + 1) % 3];
setRingerMode(newMode);
updateTileStyle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment