Using manager for controlling the volume - java

I am having problem with using audio manager for controlling volume
I am making a simple app to change ringer mode from the app but the app is crashing. The way to get instance of audio manager as directed by google is showing error. Is it possible to access and control ringer volume and mode from app?
public class MainActivity extends AppCompatActivity {
private boolean isPhoneSilent;
private AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Button toggle_Btn = findViewById(R.id.toggle_Btn);
int ringerMode = audioManager.getRingerMode();
if(ringerMode==AudioManager.RINGER_MODE_SILENT)
{
isPhoneSilent=true;
}
else
toggle_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isPhoneSilent)
{
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
isPhoneSilent=false;
}else
{
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
isPhoneSilent=true;
}
}
});
}

Related

Android play Text To Speech with audio focus (java)

I don't understand how to play text to speech with audio focus (there is spotify running some music when I try my app),
I don't understand the audioFocusChangeListener.
Here is my code:
public class MainActivity extends AppCompatActivity {
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;
public void playTTSWithAudioFocus(String toSpeak) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(audioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request temporary focus.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null,null);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playTTSWithAudioFocus("hello world");
}
}
Please help me.

Prevent Step Counter from Returning to 0 on App Closed?

I have a simple step counter taken from Google (https://github.com/google/simple-pedometer/blob/master/src/com/google/android/apps/simplepedometer/SimplePedometerActivity.java). I have adapted the Pedometer as below:
public class ActivityFragment extends Fragment implements SensorEventListener, StepListener {
private TextView textView;
private SimpleStepDetector simpleStepDetector;
private SensorManager sensorManager;
private Sensor accel;
private static final String TEXT_NUM_STEPS = "";
private int numSteps;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_activity, container, false);
textView = view.findViewById(R.id.textViewStepCounter);
textView.setTextSize(30);
// Get an instance of the SensorManager
sensorManager = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
simpleStepDetector = new SimpleStepDetector();
simpleStepDetector.registerListener(this);
return view;
}
#Override
public void onResume() {
super.onResume();
textView.setText(TEXT_NUM_STEPS + numSteps);
sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
simpleStepDetector.updateAccel(
event.timestamp, event.values[0], event.values[1], event.values[2]);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void step(long timeNs) {
numSteps++;
textView.setText(TEXT_NUM_STEPS + numSteps);
}
}
It works perfectly, however, whenever I close the application the counter returns to 0, is there any way to prevent this happening? Had a look online, however could only find options to reset, not prevent reset.
Additional question whilst I am here, is there any way to store this to Firebase?
You will have to look into local state persistence, Firebase is an online first suite. you can use Firestore Caching and rely on the cached version when offline, but it is highly recommended to look into local storage and updating your online presence infrequently.
Using local storage, you can handle real-time changes within your app and preserve any changes between the state when restarting or force closed by the user.
A few resources I was able to find:
https://www.androidauthority.com/how-to-store-data-locally-in-android-app-717190/
https://developer.android.com/training/data-storage
https://stackoverflow.com/a/61638579/2301161

Is there any option to add user-agent in streaming media Exo Player?

I'm facing a problem with exomedia player, I want to add support for some types of streaming url s but exomedia won't accept them,I have tried to much time to add the option " User AGENT" but can't turn it on, I have added my code and if there is someone who can help to fix this ?
I have tried to add User -Agent ,but in this code The player runs smooth but not some type of urls
public class ActivityStreaming extends Activity implements OnPreparedListener {
private long exitTime = 0;
private VideoView videoView;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_streaming);
url = getIntent().getStringExtra("url");
videoView = (VideoView) findViewById(R.id.video_view);
videoView.setOnPreparedListener(this);
Uri videoUri = Uri.parse(url);
videoView.setVideoURI(videoUri);
}
#Override
public void onPrepared() {
//Starts the video playback as soon as it is ready
videoView.start();
}
public void onBackPressed() {
super.onBackPressed();
}
public void closeStreaming() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_close_streaming), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
}

How to turn off music bgm(Background Music) from other java

I am making an app where bgm start from main page. But I couldn't find a way to turn it off when starts learning.
Can I remotely switch off bgm from different java file
This is my 1st java,mainmenu.class
public class mainmenu extends AppCompatActivity {
MediaPlayer bkgrdmsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Button btn = (Button) findViewById(R.id.mula);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_belajar_latihan = new Intent(getApplicationContext(), taqi.mengaji.belajar_latihan.class);
startActivity(ke_belajar_latihan);
}
});
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
bkgrdmsc.start();
}
}
This is the other file I want to remotely off the bgm when starting the learning session(as student start to learn)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.belajar_hija_baris);
Button btn=(Button) findViewById(R.id.hijaiyyah);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_hijaiyah=new Intent(getApplicationContext(),taqi.mengaji.hijaiyyah.class);
startActivity(ke_hijaiyah);
}
});
}
I want R.id.hijaiyyah to navigate to learn xml also stop bgm
Please help I'm a newbie XD
Make an singleton class and add you music playing code into it for stopping and starting and use that singleton class in all your 2 activities for eg:
public class MusicManager {
private static MusicManager refrence = null;
public static MusicManager getInstance(){
if(refrence == null){
refrence = new MusicManager ();
}
return refrence;
}
}
Add a public method to this singleton class to start and stop music
public void initalizeMediaPlayer(Context context, int musicId){
// add initalization of media player in it and loop it
MediaPlayer bkgrdmsc;
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
}
public void startPlaying(){
bkgrdmsc.start();
}
public void stopPlaying(){
bkgrdmsc.stop();
}
//Add stuff like pausing and resuming if you desire
To use this class add this to any activity you want to play music:
MusicManager.getInstance().initalizeMediaPlayer(this, R.raw.menu); // to initalize of media player
MusicManager.getInstance().startPlaying();// to start playing music
MusicManager.getInstance().stopPlaying(); // to stop playing music
You can also use service to perform this task as service runs in background. You can start and stop service any time in your code.

Make an alert only appear when app is opened

Is there a way to make an alert only appear when the app is opened? I'm creating an alert in onStart() in my MainActivity and whenever I go back to that activity in the app, it shows the alert again which can be annoying to the user. Or is there a way to create a "got it" button and then turn off the alert? Here is my code:
protected void onStart() {
super.onStart();
new AlertDialog.Builder(this)
.setTitle("Instructions")
.setMessage("Hello! To begin, select a map from the list to train with. Make sure" +
" you are on the correct floor.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
This is because when another activity comes to foreground upon your MainActivity makes your activity goes to OnPause().
Then when you go back to your MainActivity. The system calls
onStart() again. See The activity life cycle
-First Solution
public class TestActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
showAlertDialog();
}
}
private void showAlertDialog() {
// code to show alert dialog.
}
}
-Second Solution
public class TestActivity extends ActionBarActivity {
private static boolean isAlertDialogShownBefore = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isAlertDialogShownBefore) {
showAlertDialog();
isAlertDialogShownBefore = true;
}
}
private void showAlertDialog() {
// code to show alert dialog.
}
#Override
public void onBackPressed() {
isAlertDialogShownBefore = false;
super.onBackPressed();
}
}
Put that code in onCreate method of your activity. Check for saveInstanceState for null, if it is then show your alertDialog

Categories