Android: use system services to set system volume

system service

The Service written by the user is a background application Service program, which is located in the application layer of Android system. Relatively speaking, System Services can be regarded as the built-in software of Android system. It is the system background Service program running with the startup of the operating system under the Java application of Android operating system. System Service is the cornerstone of Android system. It cooperates with binder, Dalvik virtual machine and Android application to form a multi process interactive communication and interactive Service Android system.
All service cycles of Android are based on System Server. Service manager is the process of managing system services through the add of ServerManager_ The service () method adds the service to the service list to manage the service. There is an important method getSystemService() in the Activity to obtain the corresponding Object according to the passed Name, and then convert it into the corresponding service Object.

public Object getSystemService(String name);

The following are common system services:

System service name Returned object explain
WINDOW_SERVICE WindowManager Manage open window programs
LAYOUT_INFLATER_SERVICE LayoutInflater Get the View defined in xml
ACTIVITY_SERVICE ActivityManager Manage the system state of the application
POWER_SERVICE PowerManger Power service
ALARM_SERVICE AlarmManager Alarm-call Service
NOTIFICATION_SERVICE NotificationManager Status bar service
KEYGUARD_SERVICE KeyguardManager Keylock service
LOCATION_SERVICE LocationManager Location based services such as GPS
SEARCH_SERVICE SearchManager Search service
VIBRATOR SERVICE Vibrator hand Machine vibration service
CONNECTIVITY_SERVICE Connectivity Network connection service
WIFI_SERVICE WifiManager WiFi service
TELEPHONY_SERVICE TeleponyManager telephony support

System service example

Program requirements

Use the system service of Android APP to obtain and set the system volume.

functional design

First, you need to obtain the maximum value of different volume, and the setting of the volume is correct and will not cross the boundary. Then, you need to obtain the current volume as the initial value of the drag bar. Then, when the user clicks "ok", use the set method to set the system volume according to the value of the drag bar.

Code writing

AdjustVolumeDialog.java

package com.example.yinlian;

import android.app.AlertDialog;
import android.content.Context;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;

public class AdjustVolumeDialog extends AlertDialog {

    private AudioManager audioManager;
    private SeekBar seekbar1, seekbar2, seekbar3;
    private int screenWidth;
    private TextView textView1,textView2,textView3;
    private CheckBox ch;
    private Button ok, cancel;
    private Context context;

    protected AdjustVolumeDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    /**
     * setContentView() in onCreate method, otherwise the custom view of dialog will not be displayed
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;         // Screen width (pixels)
        initView();
    }

    /**
     * Customize the view of dialog
     * Set position
     */
    private void initView() {
        View root = LayoutInflater.from(getContext()).inflate(R.layout.dialog, null);
        setContentView(root);
        seekbar1 = root.findViewById(R.id.ringseekBar);
        seekbar2 = root.findViewById(R.id.mediaseekBar);
        seekbar3 = root.findViewById(R.id.alarmseekBar);
        textView1 = (TextView) findViewById(R.id.ring);
        textView2 = (TextView) findViewById(R.id.media);
        textView3 = (TextView) findViewById(R.id.Alarm);
        ch = (CheckBox)findViewById(R.id.choose);
        ok     = (Button)findViewById(R.id.ok);
        cancel = (Button)findViewById(R.id.cancel);

        seekbar1.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_RING));
        seekbar2.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        seekbar3.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM));
        int ringVolume   = audioManager.getStreamVolume(AudioManager.STREAM_RING);
        int musicVolume  = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        int alarmVolume  = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
        seekbar1.setProgress(ringVolume);
        seekbar2.setProgress(musicVolume);
        seekbar3.setProgress(alarmVolume);
        textView1.setText("Ringtone volume is:" + ringVolume);
        textView2.setText("Media volume is:" + musicVolume);
        textView3.setText("Alarm volume:" + alarmVolume);

        /* Set SeekBar listening setOnSeekBarChangeListener */
        seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            /*Called when the drag bar stops dragging */
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
            /*Called when the drag bar starts dragging*/
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            /* Called when the progress of the drag bar changes*/
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textView1.setText("Ringtone volume is:" + progress);
            }
        });

        seekbar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textView2.setText("Media volume is:" + progress);
            }
        });

        seekbar3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textView3.setText("Alarm volume:" + progress);
            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int ringVolume = seekbar1.getProgress();
                if(ch.isChecked()) {
                    audioManager.setStreamVolume(AudioManager.STREAM_RING, seekbar1.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seekbar1.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                    seekbar2.setProgress(ringVolume);
                    textView2.setText("Media volume is:" + ringVolume);
                    audioManager.setStreamVolume(AudioManager.STREAM_ALARM, seekbar1.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                    seekbar3.setProgress(ringVolume);
                    textView3.setText("Alarm volume:" + ringVolume);
                }
                else {
                    audioManager.setStreamVolume(AudioManager.STREAM_RING, seekbar1.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seekbar2.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                    audioManager.setStreamVolume(AudioManager.STREAM_ALARM, seekbar3.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                }
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        // Set the position of view in dialog
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;    //Center
        window.setAttributes(lp);
    }

    /**
     * dialog Callback on display
     * Broadcast registration
     */
    @Override
    public void show() {
        super.show();
        IntentFilter filter = new IntentFilter() ;
        filter.addAction("android.media.VOLUME_CHANGED_ACTION") ;
    }

    /**
     * dialog Callback on disappearance
     * Broadcast anti registration
     */
    @Override
    public void dismiss() {
        super.dismiss();
    }
}

Diglog.xml

Then set up a pop-up window to realize this function.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/seekLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/volume"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Volume"
            android:textSize="40dp"></TextView>

        <TextView
            android:id="@+id/ring"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Ringtone"
            android:textSize="20dp">
        </TextView>

        <SeekBar
            android:id="@+id/ringseekBar"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:maxHeight="20dp"
            android:paddingStart="15dp"
            android:paddingEnd="15dp"
            android:progressDrawable="@drawable/po_seekbar"
            android:thumb="@drawable/seekbar_thumb" />

        <TextView
            android:id="@+id/media"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Media"
            android:textSize="20dp"></TextView>

        <SeekBar
            android:id="@+id/mediaseekBar"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:maxHeight="20dp"
            android:paddingStart="15dp"
            android:paddingEnd="15dp"
            android:progressDrawable="@drawable/po_seekbar"
            android:thumb="@drawable/seekbar_thumb" />

        <TextView
            android:id="@+id/Alarm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Alarm"
            android:textSize="20dp"></TextView>

        <SeekBar
            android:id="@+id/alarmseekBar"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:maxHeight="20dp"
            android:paddingStart="15dp"
            android:paddingEnd="15dp"
            android:progressDrawable="@drawable/po_seekbar"
            android:thumb="@drawable/seekbar_thumb" />

        <CheckBox
            android:id="@+id/choose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Use incoming ring tone volume for notification"></CheckBox>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/ok"
                android:layout_width="114.0dip"
                android:layout_height="40.0dip"
                android:gravity="center"
                android:text="ok" />

            <Button
                android:id="@+id/cancel"
                android:layout_width="114.0dip"
                android:layout_height="40.0dip"
                android:layout_marginLeft="20.0dip"
                android:gravity="center"
                android:text="cancel" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>

MainActivity

package com.example.yinlian;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    Button btn;
    AdjustVolumeDialog adjustVolumeDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // You need to set a style for dialog
        adjustVolumeDialog = new AdjustVolumeDialog(this, R.style.Theme_Yinlian);
        btn = findViewById(R.id.btn);
        // Click the button to pop up the dialog box
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adjustVolumeDialog.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        if(adjustVolumeDialog!=null && adjustVolumeDialog.isShowing()) {
            adjustVolumeDialog.dismiss();
        }
        super.onDestroy();
    }
}

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.yinlian.MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="modulation"
        android:layout_marginTop="50dp"
        android:layout_gravity="center"
        android:textSize="20dp"/>

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:textSize="20dp"
        android:text="adjust">
    </Button>

</LinearLayout>

Operation effect

Open the pop-up window.

Set the new volume.

Use the incoming call volume to set the media volume and alarm volume to the incoming call volume.

reference material

Android mobile application development, edited by Yang Yi and Deputy edited by Yu dekuang, people's Posts and Telecommunications Press

Keywords: Android

Added by volleytotal.ch on Wed, 02 Feb 2022 05:47:32 +0200