下面列出了怎么用android.os.VibrationEffect的API类实例代码及写法,或者点击链接到github查看源代码。
private void startRinging() {
log("startRinging");
int ringerMode = ((AudioManager) getSystemService(AUDIO_SERVICE)).getRingerMode();
if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
return;
}
vibrator = ((Vibrator) getSystemService(VIBRATOR_SERVICE));
long[] pattern = {1500, 800, 800, 800};
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
VibrationEffect vibe = VibrationEffect.createWaveform(pattern, 0);
vibrator.vibrate(vibe);
} else {
vibrator.vibrate(pattern, 0);
}
if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
return;
}
ringtone = RingtoneManager.getRingtone(this, RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE));
ringtone.play();
}
/**
* @param context context of FingerprintService
* @param halDeviceId the HAL device ID of the associated fingerprint hardware
* @param token a unique token for the client
* @param receiver recipient of related events (e.g. authentication)
* @param userId target user id for operation
* @param groupId groupId for the fingerprint set
* @param restricted whether or not client has the {@link Manifest#MANAGE_FINGERPRINT}
* permission
* @param owner name of the client that owns this
*/
public ClientMonitor(Context context, long halDeviceId, IBinder token,
IFingerprintServiceReceiver receiver, int userId, int groupId,boolean restricted,
String owner) {
mContext = context;
mHalDeviceId = halDeviceId;
mToken = token;
mReceiver = receiver;
mTargetUserId = userId;
mGroupId = groupId;
mIsRestricted = restricted;
mOwner = owner;
mSuccessVibrationEffect = VibrationEffect.get(VibrationEffect.EFFECT_CLICK);
mErrorVibrationEffect = VibrationEffect.get(VibrationEffect.EFFECT_DOUBLE_CLICK);
try {
if (token != null) {
token.linkToDeath(this, 0);
}
} catch (RemoteException e) {
Slog.w(TAG, "caught remote exception in linkToDeath: ", e);
}
}
public boolean isHapticFeedback() {
if (effect instanceof VibrationEffect.Prebaked) {
VibrationEffect.Prebaked prebaked = (VibrationEffect.Prebaked) effect;
switch (prebaked.getId()) {
case VibrationEffect.EFFECT_CLICK:
case VibrationEffect.EFFECT_DOUBLE_CLICK:
case VibrationEffect.EFFECT_HEAVY_CLICK:
case VibrationEffect.EFFECT_TICK:
case VibrationEffect.EFFECT_POP:
case VibrationEffect.EFFECT_THUD:
return true;
default:
Slog.w(TAG, "Unknown prebaked vibration effect, "
+ "assuming it isn't haptic feedback.");
return false;
}
}
final long duration = effect.getDuration();
return duration >= 0 && duration < MAX_HAPTIC_FEEDBACK_DURATION;
}
/**
* @hide
*/
@Override
public void vibrate(int uid, String opPkg,
VibrationEffect effect, AudioAttributes attributes) {
long[] pattern;
int repeat;
if (effect instanceof VibrationEffect.OneShot) {
VibrationEffect.OneShot oneShot = (VibrationEffect.OneShot) effect;
pattern = new long[] { 0, oneShot.getDuration() };
repeat = -1;
} else if (effect instanceof VibrationEffect.Waveform) {
VibrationEffect.Waveform waveform = (VibrationEffect.Waveform) effect;
pattern = waveform.getTimings();
repeat = waveform.getRepeatIndex();
} else {
// TODO: Add support for prebaked effects
Log.w(TAG, "Pre-baked effects aren't supported on input devices");
return;
}
try {
mIm.vibrate(mDeviceId, pattern, repeat, mToken);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
private void openload_upload(String right_url) {
Link l = new Link();
l.setUrl(right_url);
l.setId(movie.getId().toString());
l.setTitle(movie.getTitle());
l.setYear(movie.getReleaseDate().substring(0,4));
new UploadOpenload(mContext,l);
progresssbar_watch.setVisibility(View.GONE);
watch.setVisibility(View.VISIBLE);
Toast.makeText(mContext,"Go Premium!", Toast.LENGTH_SHORT).show();
Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(100,VibrationEffect.DEFAULT_AMPLITUDE));
}else{
v.vibrate(100);
}
}
private static void apiIndependentVibrate(long milliseconds)
{
if (rumbleDisabled)
{
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
vibrator.vibrate(VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE));
}
else
{
vibrator.vibrate(milliseconds);
}
}
private static void apiIndependentVibrate(long[] pattern)
{
if (rumbleDisabled)
{
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1));
}
else
{
vibrator.vibrate(pattern, -1);
}
}
private void vibrate()
{
Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vb != null && vb.hasVibrator())
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
VibrationEffect vibe = VibrationEffect.createOneShot(200, DEFAULT_AMPLITUDE);
vb.vibrate(vibe);
}
else
{
//noinspection deprecation
vb.vibrate(200);
}
}
}
@Override
public void onLongTokenClick(View view, Token token, List<BigInteger> tokenIds) {
//show radio buttons of all token groups
if (adapter != null) adapter.setRadioButtons(true);
selection = tokenIds;
Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vb != null && vb.hasVibrator()) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
VibrationEffect vibe = VibrationEffect.createOneShot(200, DEFAULT_AMPLITUDE);
vb.vibrate(vibe);
} else {
//noinspection deprecation
vb.vibrate(200);
}
}
//Wait for availability to complete
waitForMapBuild();
populateButtons(token, getSelectedTokenId(tokenIds));
showButtons();
}
private void ringPhone(){
int ringerMode = ((AudioManager) getSystemService(AUDIO_SERVICE)).getRingerMode();
if(ringerMode == AudioManager.RINGER_MODE_SILENT) return;
vibrator = ((Vibrator) getSystemService(VIBRATOR_SERVICE));
long[] pattern = {1500, 800, 800, 800};
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
VibrationEffect vibe = VibrationEffect.createWaveform(pattern, 0);
vibrator.vibrate(vibe);
}else{
vibrator.vibrate(pattern, 0);
}
if(ringerMode == AudioManager.RINGER_MODE_VIBRATE) return;
ringtone = RingtoneManager.getRingtone(this, RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE));
ringtone.play();
}
@Override
public void run() {
if (isPlaying) {
handler.postDelayed(this, interval);
if (emphasisIndex >= emphasisList.size())
emphasisIndex = 0;
boolean isEmphasis = emphasisList.get(emphasisIndex);
if (listener != null)
listener.onTick(isEmphasis, emphasisIndex);
emphasisIndex++;
if (soundId != -1)
soundPool.play(soundId, 1, 1, 0, 0, isEmphasis ? 1.5f : 1);
else if (Build.VERSION.SDK_INT >= 26)
vibrator.vibrate(VibrationEffect.createOneShot(isEmphasis ? 50 : 20, VibrationEffect.DEFAULT_AMPLITUDE));
else vibrator.vibrate(isEmphasis ? 50 : 20);
}
}
@Override
public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
timePickerDialog.show(getFragmentManager(), DATE_PICK_TAG);
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && v != null) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else if (v != null) {
v.vibrate(500);
}
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
AsyncTask.execute(() -> {
for (int i = 0; i < 2; i++) {
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && v != null) {
v.vibrate(VibrationEffect.createOneShot(250, VibrationEffect.DEFAULT_AMPLITUDE));
} else if (v != null) {
v.vibrate(250);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
dateView.setText(new SimpleDateFormat("EEE, d MMM yyyy HH:mm", Locale.getDefault()).format(new Date(calendar.getTimeInMillis())));
}
@Override
public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
timePickerDialog.show(getFragmentManager(), DATE_PICK_TAG);
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && v != null) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else if (v != null) {
v.vibrate(500);
}
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 2; i++) {
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && v != null) {
v.vibrate(VibrationEffect.createOneShot(250, VibrationEffect.DEFAULT_AMPLITUDE));
} else if (v != null) {
v.vibrate(250);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
dateView.setText(new SimpleDateFormat("EEE, d MMM yyyy HH:mm", Locale.getDefault()).format(new Date(calendar.getTimeInMillis())));
}
@PluginMethod()
@SuppressWarnings("MissingPermission")
public void vibrate(PluginCall call) {
Context c = this.getContext();
int duration = call.getInt("duration", 300);
if(!hasPermission(Manifest.permission.VIBRATE)) {
call.error("Can't vibrate: Missing VIBRATE permission in AndroidManifest.xml");
return;
}
if (Build.VERSION.SDK_INT >= 26) {
((Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibratePre26(duration);
}
call.success();
}
@Override
public void onReceive(Context context, Intent arg1) {
long[] pattern = {
0, // Start immediately
500, 500, 500, 500, 500};
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createWaveform(pattern, -1));
} else {
//deprecated in API 26
if (v != null) {
v.vibrate(pattern, -1);
}
}
}
@Override
public void onShake() {
if (!isRecording) {
Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
getManager().cancel(Const.SCREEN_RECORDER_WAITING_FOR_SHAKE_NOTIFICATION_ID);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
vibrate.vibrate(500);
else
VibrationEffect.createOneShot(500, 255);
startRecording();
Toast.makeText(this, "Rec start", Toast.LENGTH_SHORT).show();
} else {
Intent recordStopIntent = new Intent(this, RecorderService.class);
recordStopIntent.setAction(Const.SCREEN_RECORDING_STOP);
startService(recordStopIntent);
Toast.makeText(this, "Rec stop", Toast.LENGTH_SHORT).show();
mShakeDetector.stop();
}
}
private void vibrate(long[] pattern) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1));
} else {
vibrator.vibrate(pattern, -1);
}
}
private Vibration(IBinder token, VibrationEffect effect,
int usageHint, int uid, String opPkg) {
this.token = token;
this.effect = effect;
this.startTime = SystemClock.elapsedRealtime();
this.startTimeDebug = System.currentTimeMillis();
this.usageHint = usageHint;
this.uid = uid;
this.opPkg = opPkg;
}
public VibrationInfo(long startTimeDebug, VibrationEffect effect,
VibrationEffect originalEffect, int usageHint, int uid, String opPkg) {
mStartTimeDebug = startTimeDebug;
mEffect = effect;
mOriginalEffect = originalEffect;
mUsageHint = usageHint;
mUid = uid;
mOpPkg = opPkg;
}
private static VibrationEffect createEffectFromTimings(long[] timings) {
if (timings == null || timings.length == 0) {
return null;
} else if (timings.length == 1) {
return VibrationEffect.createOneShot(timings[0], VibrationEffect.DEFAULT_AMPLITUDE);
} else {
return VibrationEffect.createWaveform(timings, -1);
}
}
/**
* Validate the incoming VibrationEffect.
*
* We can't throw exceptions here since we might be called from some system_server component,
* which would bring the whole system down.
*
* @return whether the VibrationEffect is valid
*/
private static boolean verifyVibrationEffect(VibrationEffect effect) {
if (effect == null) {
// Effect must not be null.
Slog.wtf(TAG, "effect must not be null");
return false;
}
try {
effect.validate();
} catch (Exception e) {
Slog.wtf(TAG, "Encountered issue when verifying VibrationEffect.", e);
return false;
}
return true;
}
@GuardedBy("mLock")
private void startVibrationInnerLocked(Vibration vib) {
Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "startVibrationInnerLocked");
try {
mCurrentVibration = vib;
if (vib.effect instanceof VibrationEffect.OneShot) {
Trace.asyncTraceBegin(Trace.TRACE_TAG_VIBRATOR, "vibration", 0);
VibrationEffect.OneShot oneShot = (VibrationEffect.OneShot) vib.effect;
doVibratorOn(oneShot.getDuration(), oneShot.getAmplitude(), vib.uid, vib.usageHint);
mH.postDelayed(mVibrationEndRunnable, oneShot.getDuration());
} else if (vib.effect instanceof VibrationEffect.Waveform) {
// mThread better be null here. doCancelVibrate should always be
// called before startNextVibrationLocked or startVibrationLocked.
Trace.asyncTraceBegin(Trace.TRACE_TAG_VIBRATOR, "vibration", 0);
VibrationEffect.Waveform waveform = (VibrationEffect.Waveform) vib.effect;
mThread = new VibrateThread(waveform, vib.uid, vib.usageHint);
mThread.start();
} else if (vib.effect instanceof VibrationEffect.Prebaked) {
Trace.asyncTraceBegin(Trace.TRACE_TAG_VIBRATOR, "vibration", 0);
long timeout = doVibratorPrebakedEffectLocked(vib);
if (timeout > 0) {
mH.postDelayed(mVibrationEndRunnable, timeout);
}
} else {
Slog.e(TAG, "Unknown vibration type, ignoring");
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR);
}
}
private void linkVibration(Vibration vib) {
// Only link against waveforms since they potentially don't have a finish if
// they're repeating. Let other effects just play out until they're done.
if (vib.effect instanceof VibrationEffect.Waveform) {
try {
vib.token.linkToDeath(vib, 0);
} catch (RemoteException e) {
return;
}
}
}
private void doVibratorOn(long millis, int amplitude, int uid, int usageHint) {
Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "doVibratorOn");
try {
synchronized (mInputDeviceVibrators) {
if (amplitude == VibrationEffect.DEFAULT_AMPLITUDE) {
amplitude = mDefaultVibrationAmplitude;
}
if (DEBUG) {
Slog.d(TAG, "Turning vibrator on for " + millis + " ms" +
" with amplitude " + amplitude + ".");
}
noteVibratorOnLocked(uid, millis);
final int vibratorCount = mInputDeviceVibrators.size();
if (vibratorCount != 0) {
final AudioAttributes attributes =
new AudioAttributes.Builder().setUsage(usageHint).build();
for (int i = 0; i < vibratorCount; i++) {
mInputDeviceVibrators.get(i).vibrate(millis, attributes);
}
} else {
// Note: ordering is important here! Many haptic drivers will reset their
// amplitude when enabled, so we always have to enable frst, then set the
// amplitude.
vibratorOn(millis);
doVibratorSetAmplitude(amplitude);
}
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR);
}
}
VibrateThread(VibrationEffect.Waveform waveform, int uid, int usageHint) {
mWaveform = waveform;
mUid = uid;
mUsageHint = usageHint;
mTmpWorkSource.set(uid);
mWakeLock.setWorkSource(mTmpWorkSource);
}
private int runVibrate() {
Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "runVibrate");
try {
try {
final int zenMode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.ZEN_MODE);
if (zenMode != Settings.Global.ZEN_MODE_OFF) {
try (PrintWriter pw = getOutPrintWriter();) {
pw.print("Ignoring because device is on DND mode ");
pw.println(DebugUtils.flagsToString(Settings.Global.class, "ZEN_MODE_",
zenMode));
return 0;
}
}
} catch (SettingNotFoundException e) {
// ignore
}
final long duration = Long.parseLong(getNextArgRequired());
if (duration > MAX_VIBRATION_MS) {
throw new IllegalArgumentException("maximum duration is " + MAX_VIBRATION_MS);
}
String description = getNextArg();
if (description == null) {
description = "Shell command";
}
VibrationEffect effect =
VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE);
vibrate(Binder.getCallingUid(), description, effect, AudioAttributes.USAGE_UNKNOWN,
mToken);
return 0;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR);
}
}
SleepTimer(TextView sleepCountDownTV, MediaPlayerService mediaPlayer, SensorManager sensorMng,
Context context) {
mSleepCountDownTV = sleepCountDownTV;
mPlayer = mediaPlayer;
mSensorMng = sensorMng;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
mContext = context;
mShakeDetector = new ShakeDetector(mShakeForceRequired) {
@Override
public void shakeDetected() {
boolean vibrateOnShakeReset = mSharedPreferences.getBoolean(context.getString(R.string.settings_vibrate_shake_reset_key), Boolean.getBoolean(context.getString(R.string.settings_vibrate_shake_reset_default)));
if (vibrateOnShakeReset) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (v != null) {
v.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE));
}
} else {
if (v != null) {
//deprecated in API 26
v.vibrate(100);
}
}
}
restartTimer();
startTimer(false);
}
};
}
public static void Vibrate(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(100);
}
}