activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical" android:background="#d1dcce" > <TextView android:id="@+id/tv_stats" android:layout_width="match_parent" android:layout_height="wrap_content" android:textStyle="bold" android:textSize="25sp" /> <Button android:id="@+id/btn_get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get Media Volume Level" /> </LinearLayout>
MainActivity.java
package com.cfsuman.me.androidcodesnippets; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Context mContext; private Activity mActivity; private LinearLayout mRootLayout; private Button mBtnGet; private TextView mTVStats; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the application context mContext = getApplicationContext(); mActivity = MainActivity.this; // Get the widget reference from xml layout mRootLayout = findViewById(R.id.root_layout); mBtnGet = findViewById(R.id.btn_get); mTVStats = findViewById(R.id.tv_stats); // Click listener for the button mBtnGet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* AudioManager AudioManager provides access to volume and ringer mode control. Instances of this class must be obtained using Context.getSystemService(Class) with the argument AudioManager.class or Context.getSystemService(String) with the argument Context.AUDIO_SERVICE. */ // Get the AudioManager instance AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); /* int getStreamVolume (int streamType) Returns the current volume index for a particular stream. Parameters streamType int : The stream type whose volume index is returned. Returns int : The current volume index for the stream. */ // Get the music current volume level int music_volume_level = am.getStreamVolume(AudioManager.STREAM_MUSIC); // Get the device music maximum volume level int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); // Display the media volume level stats on text view mTVStats.setText("Media Max Volume : " + max + "\nMedia Current Volume : " + music_volume_level); } }); } }
Komentar
Posting Komentar