I am currently making an app with a SeekBar in which the SeekBar controls the Music Volume, Ringtone Volume, and Alarm Volume. It works fine but whenever I try to code in a button to set the phone to vibrate, it either crashes the app or it just breaks the code so the SeekBar never changes the volumes. Any help on how to achieve a button to set the phone to vibrate will be greatly appreciated. Thanks.
import android.app.*;
import android.os.*;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
private SeekBar Volume = null;
private AudioManager audioManager = null;
private TextView volumeValue;
private Vibrator sVibrate;
private ToggleButton vibrateButton;
final private String volumeIs = "Current Volume: ";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.main);
allVolumes();
}
private void allVolumes()
{
try
{
Volume = (SeekBar) findViewById(R.id.Volume);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Volume.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
Volume.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
sVibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrateButton = (ToggleButton) findViewById(R.id.vibrateButton);
volumeValue = (TextView) findViewById(R.id.volumeValue);
volumeValue.setText(volumeIs
+ Integer.toString(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)));
Volume.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress,
boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
audioManager.setStreamVolume(AudioManager.STREAM_RING,
progress, 0);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM,
progress, 0);
volumeValue.setText(volumeIs
+ Integer.toString(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)));
}
});
}
catch (Exception e)
{
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(R.string.catch_error);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Quit",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
finish();
}
});
builder.setNegativeButton("Ignore",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
Toast.makeText(
MainActivity.this,
"This app will not work right unless you restart.",
Toast.LENGTH_LONG).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
Any help on how to achieve a button to set the phone to vibrate will be greatly appreciated.
Do you mean, switch the phone to the vibration mode? Try this:
(AudioManager) getSystemService(AUDIO_SERVICE)).setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Related
I have a strange problem implementing Google Reward Video. In test mode (with google ad-id) works perfect first time, but not loading video in the second time. In production (with my ids) not loading video at all. Here is my code:
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import eu.healthydev.quizhero.Common.Common;
import eu.healthydev.quizhero.Model.Question;
import eu.healthydev.quizhero.Model.QuestionScore;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class DoneActivity extends AppCompatActivity implements RewardedVideoAdListener{
Button btnTryAgain, exit_game;
TextView txtResultScore, getTxtResultQuestion;
ProgressBar progressBar;
FirebaseDatabase database;
DatabaseReference question_score;
//VideoAd Award
private static final String AD_UNIT_ID = "ca-app-pub-5883754622051955/6179215953";
private static final String APP_ID = "ca-app-pub-5883754622051955~8837168889";
private int coinCount;
private TextView coinCountText;
private RewardedVideoAd rewardedVideoAd;
private Button showVideoButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_done);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this, APP_ID);
rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
rewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
database = FirebaseDatabase.getInstance();
question_score = database.getReference("Question_Score");
txtResultScore = (TextView)findViewById(R.id.txtTotalScore);
getTxtResultQuestion =(TextView)findViewById(R.id.txtTotalQuestion);
progressBar = (ProgressBar)findViewById(R.id.doneProgressBar);
// Create the "retry" button, which tries to show an interstitial between game plays.
btnTryAgain = (Button)findViewById(R.id.btnTryAgain);
exit_game = (Button) findViewById(R.id.exit_game);
btnTryAgain.setVisibility(View.INVISIBLE);
btnTryAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DoneActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
showVideoButton = findViewById(R.id.show_video_button);
showVideoButton.setVisibility(View.VISIBLE);
showVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
exit_game.setVisibility(View.VISIBLE);
exit_game.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
// Display current coin count to user.
coinCountText = findViewById(R.id.coin_count_text);
coinCount = 0;
coinCountText.setText("Coins: " + coinCount);
//Get data from bundle and set view
Bundle extra = getIntent().getExtras();
if(extra != null)
{
int score = extra.getInt("SCORE");
int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtResultScore.setText(String.format("SCORE : %d", score));
getTxtResultQuestion.setText(String.format("PASSED : %d /%d", correctAnswer,totalQuestion));
progressBar.setMax(totalQuestion);
progressBar.setProgress(correctAnswer);
//Upload points to Database
question_score.child(String.format("%s_%s", Common.currentUser.getUserName(),
Common.categoryID))
.setValue(new QuestionScore(String.format("%s_%s", Common.currentUser.getUserName(),
Common.categoryID),
Common.currentUser.getUserName(),
String.valueOf(score),
Common.categoryID,
Common.categoryName));
}
}
private void loadRewardedVideoAd() {
if (!rewardedVideoAd.isLoaded()) {
rewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
}
}
private void addCoins(int coins) {
coinCount += coins;
coinCountText.setText("Coins: " + coinCount);
}
private void showRewardedVideo() {
showVideoButton.setVisibility(View.INVISIBLE);
exit_game.setVisibility(View.INVISIBLE);
if (rewardedVideoAd.isLoaded()) {
rewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
btnTryAgain.setVisibility(View.INVISIBLE);
showVideoButton.setVisibility(View.VISIBLE);
exit_game.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "Ad Video Failed to Load", Toast.LENGTH_SHORT).show();
showVideoButton.setVisibility(View.VISIBLE);
exit_game.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" You ve got one free try!", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
btnTryAgain.setVisibility(View.VISIBLE);
showVideoButton.setVisibility(View.INVISIBLE);
exit_game.setVisibility(View.INVISIBLE);
addCoins(1);
Intent intent = new Intent(DoneActivity.this, HomeActivity.class);
startActivity(intent);
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
System.exit(0);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
I double checked my ids and are correct. Probably my code too as it works ane time exactly as it has to do. I will appriciate any help or idea.
From: https://developers.google.com/admob/android/rewarded-video
#Override
public void onRewardedVideoAdClosed() {
// Load the next rewarded video ad.
loadRewardedVideoAd();
}
We need to re-load once the first one is closed.
My app is working fine due to same. Hope that helps.
i have the next code, and i want to put a method (i am newbie and don´t get how can i do that). Because when i am playing the sound and finish the app, this continue and can´t stop it, and if i put mp.pause(); before this finish(by Exit button) works, BUT if i NEVER pressed Play, my app don´t play the sound after this.
With methods i mean: if (SoundPlaying) mp.pause();
Code:
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AdView adView = (AdView) findViewById(R.id.adView);
adView.loadAd(new AdRequest());
final MediaPlayer mp = MediaPlayer.create(this, R.raw.rain);
final ImageView Play = (ImageView) findViewById(R.id.imageView1);
Play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Animation Rotate = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
Play.startAnimation(Rotate);
mp.start();
}});
final ImageView Pause = (ImageView) findViewById(R.id.imageView2);
Pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.pause();
Animation Rotate = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
Pause.startAnimation(Rotate);
}});
final ImageView Exit = (ImageView) findViewById(R.id.imageView3);
Exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Do you want to exit?");
// Setting Dialog Message
alertDialog.setMessage("If you liked the app, please Rate us!");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.exit2);
// Setting Positive Yes Button
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// User pressed Yes button. Write Logic Here
finish();
}
});
// Setting Neutral Button
alertDialog.setNeutralButton("Rate us!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Couldn´t launch Google Play",
Toast.LENGTH_LONG).show();
}
}
});
// Setting Positive "Cancel" Button
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
});
//Orientación de la APP Vertical
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I think you mean "How do i implement an if statement" rather than method. You need to check if music is playing, and stop it if it is. Then once it has been stopped you can finish the activity.
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (mp.isPlaying()){
mp.stop();
}
finish();
}
});
When you are pausing sound after that write int length = mp.getCurrentPosition();
Like-
int length;
mp.pause();
length = mp.getCurrentPosition();
When user click no button write following code to continue playing from recent postion.
mp.seekTo(length);
mp.start();
And for yes button #Nood already answered.
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class pushke extends Activity {
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
MediaPlayer mp;
MediaPlayer mp2;
MediaPlayer mp3;
MediaPlayer mp4;
MediaPlayer mp5;
MediaPlayer mp6;
SeekBar seekGuns;
RelativeLayout rguns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
rguns=(RelativeLayout) findViewById(R.id.rguns);
mp=MediaPlayer.create(this, R.raw.hekler);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp2.isPlaying()){
mp2.pause();
mp2.seekTo(0);
}
if (mp3.isPlaying()){
mp3.pause();
mp3.seekTo(0);
}
if (mp4.isPlaying()){
mp4.pause();
mp4.seekTo(0);
}
if (mp5.isPlaying()){
mp5.pause();
mp5.seekTo(0);
}
if (mp6.isPlaying()){
mp6.pause();
mp6.seekTo(0);
}
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekGuns);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
int index = seekGuns.getProgress();
seekGuns.setProgress(index + 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
int index = seekGuns.getProgress();
seekGuns.setProgress(index - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
I am trying to connect hardware buttons to my seekbar so when I click on volume buttons, seekbar which is used for volume, increase-decrease depending on which button I pressed.
I got this code which is supposed to be working, but I have no idea why it's not working in my case, everytime I launch my app on phone as emulator, and use hardware volume button app crashes.
I get this in LoGcat but Ican't figure out how to fix it or where is the problem because eclipse is not showing me any errors.
Here is my logcat: http://i.imgur.com/o4qSvCv.png
This is because you have declared two Seekbar variables.
private SeekBar volumeSeekbar = null;
SeekBar seekGuns;
and in your onKeyDown method you are using seekGuns named variable which is not initialized.
So you have two option.
1) Initialize means find the id for seekguns variable.
2) Use volumeSeekbar instead of seekguns in onKeyDown method.
i build an app , and i want to mute and unmute just the sound of this app..
i found this code to mute the sound:
AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
It mutes all the sound of the device and disables the setting of the device to set the sound, not just the sound of the app..
And i found this code to unmute the sound:
AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
When i have muted the sound, and i clicked the button that contains this code, this code is not running and the sound setting of my device is still disabled..
I just want to mute and unmute the sound of my app, not my device.. Any correction?
Try this code:
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
Button play, mute, data, max;
private boolean VolIsMute;
AudioManager manager;
int currentVolume;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
VolIsMute = false;
init();
}
public void isMute() {
if (VolIsMute) {
manager.setStreamMute(AudioManager.STREAM_MUSIC, false);
VolIsMute = false;
} else {
manager.setStreamMute(AudioManager.STREAM_MUSIC, true);
VolIsMute = true;
}
}
public void init() {
max = (Button) findViewById(R.id.max);
play = (Button) findViewById(R.id.start);
mute = (Button) findViewById(R.id.mute);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
MediaPlayer mp = MediaPlayer.create(
getApplicationContext(), R.raw.abc);
mp.start();
} catch (NullPointerException e) {
e.printStackTrace();
Log.d("WTF", "error: " + e);
}
}
});
}
public void mute(View view) {
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (currentVolume == 0) {
Toast.makeText(getApplicationContext(),
" Volume is " + currentVolume +"Press unmute", Toast.LENGTH_SHORT).show();
} else {
isMute();
}
}
public void checvol(View view) {
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (currentVolume != 0) {
Toast.makeText(getApplicationContext(),
"Press unmute", Toast.LENGTH_SHORT).show();
} else {
isMute();
}
}
}
I used two buttons one for mute and other for unmute.
Check the current volume first and then do appropriately with if -else.
For those who simplify this,don't forget to post the code.
I know how to control volume of media player from seekbar.But how can i do to change system volume from seekbar in android.
Use AudioManager and methods like adjustStreamVolume(). Here is a sample application that uses SeekBar widgets to adjust the volumes of various streams.
The following code can be used :
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}