Example usage for android.content Context VIBRATOR_SERVICE

List of usage examples for android.content Context VIBRATOR_SERVICE

Introduction

In this page you can find the example usage for android.content Context VIBRATOR_SERVICE.

Prototype

String VIBRATOR_SERVICE

To view the source code for android.content Context VIBRATOR_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.Vibrator for interacting with the vibration hardware.

Usage

From source file:com.mobileman.moments.android.frontend.activity.IncomingCallActivity.java

private void doCleanup() {
    if (delayHandler != null) {
        delayHandler.removeCallbacksAndMessages(null);
    }//from  w  w w. j  a  va2  s.c  o m
    if (mPlayer != null) {
        try {
            mPlayer.stop();
        } catch (IllegalStateException e) {
            // we don't care
        }
        mPlayer.release();
        mPlayer = null;
    }
    streamingUser = null;
    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.cancel();
}

From source file:com.oginotihiro.datepicker.DatePickerDialog.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Activity activity = getActivity();//  w  w  w .  j  a v  a 2 s .  com
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    mVibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);

    if (savedInstanceState != null) {
        mCalendar.set(Calendar.YEAR, savedInstanceState.getInt(KEY_SELECTED_YEAR));
        mCalendar.set(Calendar.MONTH, savedInstanceState.getInt(KEY_SELECTED_MONTH));
        mCalendar.set(Calendar.DAY_OF_MONTH, savedInstanceState.getInt(KEY_SELECTED_DAY));

        mMinYear = savedInstanceState.getInt(KEY_YEAR_START);
        mMaxYear = savedInstanceState.getInt(KEY_YEAR_END);
        mWeekStart = savedInstanceState.getInt(KEY_WEEK_START);

        mVibrate = savedInstanceState.getBoolean(KEY_VIBRATE);
        mColor = savedInstanceState.getInt(KEY_COLOR);
        mDarkColor = savedInstanceState.getInt(KEY_DARK_COLOR);
    }
}

From source file:io.github.carlorodriguez.morningritual.MainActivity.java

private void notifyStepFinish() {
    if (vibrateWhenStepFinish()) {
        ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(500);
    }/*from w w  w  . ja  v a  2 s .c  o  m*/

    if (soundWhenStepFinish()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION).build();

            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

            MediaPlayer.create(this, R.raw.sound, audioAttributes, audioManager.generateAudioSessionId())
                    .start();
        } else {
            try {
                playLegacyNotificationSound();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, R.string.cannot_load_notification_sound, Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
}

From source file:hongik.android.project.best.HistoryActivity.java

public void recommendReview() {
    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(500);/*from   ww w.jav  a  2s .  c o m*/

    Intent reviewIntent = new Intent(this, ReviewActivity.class);
    reviewIntent.putExtra("BUID", nowPeripheral.getBDAddress().replace(":", ""));
    reviewIntent.putExtra("CID", cid);
    nowPeripheral = null;
    startActivityForResult(reviewIntent, 2);
}

From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java

@Override
public void onReceive(Context context, Intent pintent) {
    Log.v(TAG, "ALARM: received alarm");

    NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {//  w  ww  .  j  ava 2s .c o  m
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    // Cancel notification and return...
    if (CANCEL_NOTIFICATION.equals(pintent.getAction())) {
        Log.v(TAG, "Cancelling notification...");

        mNM.cancelAll();
        return;
    }

    // ...or display a new one

    Log.v(TAG, "Showing notification...");

    player = new MediaPlayer();

    int setTime = pintent.getIntExtra("SetTime", 0);
    String setTimeStr = TimerUtils.time2humanStr(context, setTime);
    Log.v(TAG, "Time: " + setTime);

    CharSequence text = context.getText(R.string.Notification);
    CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr);

    // Load the settings 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean led = prefs.getBoolean("LED", true);
    boolean vibrate = prefs.getBoolean("Vibrate", true);
    String notificationUri = "";

    boolean useAdvTime = prefs.getBoolean("useAdvTime", false);
    String advTimeString = prefs.getString("advTimeString", "");
    String[] advTime = null;
    int advTimeIndex = 1;

    if (useAdvTime && advTimeString.length() > 0) {
        advTime = advTimeString.split("\\^");
        advTimeIndex = prefs.getInt("advTimeIndex", 1);
        String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound

        if (thisAdvTime.length == 3)
            notificationUri = thisAdvTime[1];
        if (notificationUri.equals("sys_def"))
            notificationUri = prefs.getString("NotificationUri",
                    "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);
    } else
        notificationUri = prefs.getString("NotificationUri",
                "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done));
        Intent ttsIntent = new Intent(context, TTSService.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest);

    Uri uri = null;

    // Play a sound!
    if (!notificationUri.equals(""))
        uri = Uri.parse(notificationUri);

    // Vibrate
    if (vibrate && uri == null) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    // Have a light
    if (led) {
        mBuilder.setLights(0xff00ff00, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, TimerActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(TimerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Create intent for cancelling the notification
    Context appContext = context.getApplicationContext();
    Intent intent = new Intent(appContext, TimerReceiver.class);
    intent.setAction(CANCEL_NOTIFICATION);

    // Cancel the pending cancellation and create a new one
    PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (uri != null) {

        //remove notification sound
        mBuilder.setSound(null);

        try {
            if (player != null && player.isPlaying()) {
                player.release();
                player = new MediaPlayer();
            }

            int currVolume = prefs.getInt("tone_volume", 0);
            if (currVolume != 0) {
                float log1 = (float) (Math.log(100 - currVolume) / Math.log(100));
                player.setVolume(1 - log1, 1 - log1);
            }
            player.setDataSource(context, uri);
            player.prepare();
            player.setLooping(false);
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.start();
            if (vibrate) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(1000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("AutoClear", false)) {
        // Determine duration of notification sound
        int duration = 5000;
        if (uri != null) {
            MediaPlayer cancelPlayer = new MediaPlayer();
            try {
                cancelPlayer.setDataSource(context, uri);
                cancelPlayer.prepare();
                duration = Math.max(duration, cancelPlayer.getDuration() + 2000);
            } catch (java.io.IOException ex) {
                Log.e(TAG, "Cannot get sound duration: " + ex);
                duration = 30000; // on error, default to 30 seconds
            } finally {
                cancelPlayer.release();
            }
            cancelPlayer.release();
        }
        Log.v(TAG, "Notification duration: " + duration + " ms");
        // Schedule cancellation
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration,
                pendingCancelIntent);
    }

    if (useAdvTime && advTimeString.length() > 0) {
        Intent broadcast = new Intent();

        SharedPreferences.Editor editor = prefs.edit();
        if (advTimeIndex < advTime.length) {
            editor.putInt("advTimeIndex", advTimeIndex + 1);

            String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound

            int time = Integer.parseInt(thisAdvTime[0]);

            broadcast.putExtra("time", time);

            // Save new time
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);

            // editor.putString("NotificationUri", thisAdvTime[1]);

            mNM.cancelAll();
            Log.v(TAG, "Starting next iteration of the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);
        } else {
            broadcast.putExtra("stop", true);
            editor.putInt("advTimeIndex", 1);

        }
        broadcast.setAction(BROADCAST_RESET);
        context.sendBroadcast(broadcast);

        editor.apply();

    } else if (prefs.getBoolean("AutoRestart", false)) {
        int time = pintent.getIntExtra("SetTime", 0);
        if (time != 0) {

            mNM.cancel(0);
            Log.v(TAG, "Restarting the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);

            // Save new time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);
            editor.apply();

            Intent broadcast = new Intent();
            broadcast.putExtra("time", time);
            broadcast.setAction(BROADCAST_RESET);
            context.sendBroadcast(broadcast);

        }
    }

    mNotificationManager.notify(0, mBuilder.build());

    Log.d(TAG, "ALARM: alarm finished");

}

From source file:mai.whack.StickyNotesActivity.java

private void openBrowser(String url) {
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        url = "http://" + url;
    }//from   w w  w. ja va2 s  .c  om
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(300);

    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    startActivity(browserIntent);
}

From source file:de.uni_weimar.m18.anatomiederstadt.element.Quiz4Buttons.java

@Override
public void onClick(View v) {
    Button correctButton;//from  w w  w .  j a v a  2  s  . c  o m
    switch (mCorrect) {
    case 1:
        correctButton = (Button) getActivity().findViewById(R.id.button1);
        break;
    case 2:
        correctButton = (Button) getActivity().findViewById(R.id.button2);
        break;
    case 3:
        correctButton = (Button) getActivity().findViewById(R.id.button3);
        break;
    case 4:
        correctButton = (Button) getActivity().findViewById(R.id.button4);
        break;
    default:
        correctButton = (Button) getActivity().findViewById(R.id.button1);
    }

    mTries += 1;

    if (v.getId() == correctButton.getId()) { // correct answer
        String congratulations = String.format(getString(R.string.congratulations_format_string), mPoints);
        SnackbarManager.show(Snackbar.with(getActivity()).position(Snackbar.SnackbarPosition.TOP).margin(32, 32)
                .backgroundDrawable(R.drawable.points_snackbar_shape).text(congratulations)
                .eventListener(new EventListener() {
                    @Override
                    public void onShow(Snackbar snackbar) {

                    }

                    @Override
                    public void onShowByReplace(Snackbar snackbar) {

                    }

                    @Override
                    public void onShown(Snackbar snackbar) {

                    }

                    @Override
                    public void onDismiss(Snackbar snackbar) {

                    }

                    @Override
                    public void onDismissByReplace(Snackbar snackbar) {

                    }

                    @Override
                    public void onDismissed(Snackbar snackbar) {
                        if (mListener != null) {
                            mListener.correctAnswerAction(mTarget);
                        }
                    }
                }));
        //Toast.makeText(getActivity(), "RRRRRRRICHTIG!", Toast.LENGTH_SHORT).show();
        submitPointsToBackend(mPoints);

    } else if (mTries >= mMaxTries) { // user entered wrong answer too often
        String sorry = getString(R.string.sorry_correct_answer) + "\n\"" + correctButton.getText() + "\"";
        new MaterialDialog.Builder(getActivity()).title(getString(R.string.sorry_correct_answer_dialog_title))
                .content(sorry).positiveText(getString(R.string.sorry_dismiss))
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        if (mListener != null) { // go to next page anyway
                            mListener.correctAnswerAction(mTarget);
                        }
                    }
                }).show();
    } else { // wrong answer
        mPoints -= mPenalty;
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(300);
        new MaterialDialog.Builder(getActivity()).title(getString(R.string.wrong_answer_dialog_title))
                .content(mHint).positiveText(R.string.wrong_answer_dismiss).show();
        //Toast.makeText(getActivity(), "BZZZZZZZZZTTTT... falsch!", Toast.LENGTH_SHORT).show();
    }
}

From source file:ca.mudar.snoozy.receiver.PowerConnectionReceiver.java

private void nativeVibrate(Context context, boolean hasVibration) {
    if (hasVibration) {
        final Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

        vibrator.vibrate(Const.VIBRATION_DURATION);
    }/* www.ja  v  a2 s . c o  m*/
}

From source file:com.finchuk.clock2.alarms.ui.ExpandedAlarmViewHolder.java

@OnClick(com.finchuk.clock2.R.id.vibrate)
void onVibrateToggled() {
    final boolean checked = mVibrate.isChecked();
    if (checked) {
        Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(300);//from w  w  w.  j  av  a  2s.  com
    }
    final Alarm oldAlarm = getAlarm();
    Alarm newAlarm = oldAlarm.toBuilder().vibrates(checked).build();
    oldAlarm.copyMutableFieldsTo(newAlarm);
    persistUpdatedAlarm(newAlarm, false);
}

From source file:com.hx.hxchat.activity.ChatHistoryFragment.java

private void initData() {
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override//  w  w  w .j av  a2  s  . com
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            EMContact emContact = adapter.getItem(position);
            if (adapter.getItem(position).getUsername().equals(BaseApplication.getApplication().getUserName()))
                Toast.makeText(getActivity(), "??", 0).show();
            else {
                if (EMChatManager.getInstance().isConnected()) {
                    // ??
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if (emContact instanceof EMGroup) {
                        // it is group chat
                        intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
                        intent.putExtra("groupId", ((EMGroup) emContact).getGroupId());
                    } else {
                        // it is single chat
                        intent.putExtra("userId", emContact.getUsername());
                        intent.putExtra("userName", emContact.getNick());

                        // intent.putExtra("userId",
                        // adapter.m_User_s.get(position).getM_name());
                    }
                    startActivity(intent);
                } else {
                    BaseApplication.getApplication().isHxLogined = false;
                    // BaseApplication.getApplication().Hxlogin();
                    Toast.makeText(getActivity(), "???", 0).show();
                }
            }
        }
    });

    // ??
    listView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // ??
            if (getActivity().getWindow()
                    .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                if (getActivity().getCurrentFocus() != null)
                    inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });

    listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if (vibrator == null)
                vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);

            long[] pattern = { 100, 100 };
            vibrator.vibrate(30);

            String title = "";
            EMContact item = adapter.getItem(position);

            if (item instanceof EMGroup) {
                title = ((EMGroup) item).getGroupName();
            } else {

                title = item.getNick();

            }

            showMyDialog(title, adapter, position);
            return false;
        }
    });
    //      registerForContextMenu(listView);

    if (!CommonUtils.isNetWorkConnected(context)) {
        return;
    }
    // ?

    new GetDataAcyncTask().execute();
    setLoadDataComplete(new isLoadDataListener() {
        @Override
        public void loadStart() {
            onPostExecuting = true;
            if (!progressDialog.isShowing() && !hidden) {
                // progressDialog.show();

            }
        }

        @Override
        public void loadComplete() {
            onPostExecuting = false;
            if (progressDialog.isShowing() && !hidden) {
                // progressDialog.dismiss();

            }
        }

        @Override
        public void progress(int progress) {

        }
    });

}