我目前正在制作一个带有 SeekBar 的应用程序,其中 SeekBar 控制音乐音量、铃声音量和闹钟音量。它工作正常,但每当我尝试在按钮中编写代码以将手机设置为振动时,它要么使应用程序崩溃,要么只是破坏代码,因此 SeekBar 永远不会改变音量。任何有关如何实现将手机设置为振动的按钮的帮助将不胜感激。谢谢。
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();
}
}
}