Example usage for android.os Vibrator vibrate

List of usage examples for android.os Vibrator vibrate

Introduction

In this page you can find the example usage for android.os Vibrator vibrate.

Prototype

@RequiresPermission(android.Manifest.permission.VIBRATE)
    public void vibrate(VibrationEffect vibe) 

Source Link

Usage

From source file:com.flyingcrop.ScreenCaptureFragment.java

void notifySS(Bitmap bitmap, String date, String dir) {

    File file = new File(dir);

    if (file.exists()) {
        Log.d("FlyingCrop", "O ficheiro a ser partilhado existe");
    } else {//from www.jav a2s.  c o m
        Log.d("FlyingCrop", "O ficheiro a ser partilhado no existe");
    }

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/png");
    share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));

    PendingIntent i = PendingIntent.getActivity(getActivity(), 0,
            Intent.createChooser(share, getResources().getString(R.string.fragment_share)),
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "image/png");
    PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notif = new Notification.Builder(getActivity()).setContentTitle(date + ".png")
            .setContentText(getResources().getString(R.string.fragment_img_preview))
            .addAction(android.R.drawable.ic_menu_share, getResources().getString(R.string.fragment_share), i)
            .setSmallIcon(com.flyingcrop.R.drawable.ab_ico).setLargeIcon(bitmap)
            .setStyle(new Notification.BigPictureStyle().bigPicture(bitmap)).setContentIntent(pendingIntent)
            .setPriority(Notification.PRIORITY_MAX)

            .build();
    final SharedPreferences settings = getActivity().getSharedPreferences("data", 0);

    NotificationManager notificationManager = (NotificationManager) getActivity()
            .getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, notif);

    if (settings.getBoolean("vibration", false)) {
        Vibrator v = (Vibrator) this.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(100);
    }
}

From source file:za.co.neilson.alarm.preferences.AlarmPreferencesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.alarm_preferences);

    pref = getSharedPreferences("AppPref", MODE_PRIVATE);
    email = getIntent().getStringExtra("email");
    Log.d("? ???!!! ", "" + email);

    Bundle bundle = getIntent().getExtras();
    if (bundle != null && bundle.containsKey("alarm")) {
        setMathAlarm((Alarm) bundle.getSerializable("alarm"));
    } else {/*from ww  w. ja  v  a  2  s . c  o m*/
        setMathAlarm(new Alarm());
    }
    if (bundle != null && bundle.containsKey("adapter")) {
        setListAdapter((AlarmPreferenceListAdapter) bundle.getSerializable("adapter"));
    } else {
        setListAdapter(new AlarmPreferenceListAdapter(this, getMathAlarm()));
    }

    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id) {
            final AlarmPreferenceListAdapter alarmPreferenceListAdapter = (AlarmPreferenceListAdapter) getListAdapter();
            final AlarmPreference alarmPreference = (AlarmPreference) alarmPreferenceListAdapter
                    .getItem(position);

            AlertDialog.Builder alert;
            v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
            switch (alarmPreference.getType()) {
            case BOOLEAN:
                CheckedTextView checkedTextView = (CheckedTextView) v;
                boolean checked = !checkedTextView.isChecked();
                ((CheckedTextView) v).setChecked(checked);
                switch (alarmPreference.getKey()) {
                case ALARM_ACTIVE:
                    alarm.setAlarmActive(checked);
                    break;
                case ALARM_VIBRATE:
                    alarm.setVibrate(checked);
                    if (checked) {
                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                        vibrator.vibrate(1000);
                    }
                    break;
                }
                alarmPreference.setValue(checked);
                break;
            case STRING:

                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                // Set an EditText view to get user input
                final EditText input = new EditText(AlarmPreferencesActivity.this);

                input.setText(alarmPreference.getValue().toString());

                alert.setView(input);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        alarmPreference.setValue(input.getText().toString());

                        if (alarmPreference.getKey() == Key.ALARM_NAME) {
                            alarm.setAlarmName(alarmPreference.getValue().toString());
                        }

                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }
                });
                alert.show();
                break;
            case LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] items = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < items.length; i++)
                    items[i] = alarmPreference.getOptions()[i];

                alert.setItems(items, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (alarmPreference.getKey()) {
                        case ALARM_DIFFICULTY:
                            Alarm.Difficulty d = Alarm.Difficulty.values()[which];
                            alarm.setDifficulty(d);
                            break;
                        case ALARM_TONE:
                            alarm.setAlarmTonePath(alarmPreferenceListAdapter.getAlarmTonePaths()[which]);
                            if (alarm.getAlarmTonePath() != null) {
                                if (mediaPlayer == null) {
                                    mediaPlayer = new MediaPlayer();
                                } else {
                                    if (mediaPlayer.isPlaying())
                                        mediaPlayer.stop();
                                    mediaPlayer.reset();
                                }
                                try {
                                    // mediaPlayer.setVolume(1.0f, 1.0f);
                                    mediaPlayer.setVolume(0.2f, 0.2f);
                                    mediaPlayer.setDataSource(AlarmPreferencesActivity.this,
                                            Uri.parse(alarm.getAlarmTonePath()));
                                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                                    mediaPlayer.setLooping(false);
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();

                                    // Force the mediaPlayer to stop after 3
                                    // seconds...
                                    if (alarmToneTimer != null)
                                        alarmToneTimer.cancel();
                                    alarmToneTimer = new CountDownTimer(3000, 3000) {
                                        @Override
                                        public void onTick(long millisUntilFinished) {

                                        }

                                        @Override
                                        public void onFinish() {
                                            try {
                                                if (mediaPlayer.isPlaying())
                                                    mediaPlayer.stop();
                                            } catch (Exception e) {

                                            }
                                        }
                                    };
                                    alarmToneTimer.start();
                                } catch (Exception e) {
                                    try {
                                        if (mediaPlayer.isPlaying())
                                            mediaPlayer.stop();
                                    } catch (Exception e2) {

                                    }
                                }
                            }
                            break;
                        default:
                            break;
                        }
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }

                });

                alert.show();
                break;
            case MULTIPLE_LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] multiListItems = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < multiListItems.length; i++)
                    multiListItems[i] = alarmPreference.getOptions()[i];

                boolean[] checkedItems = new boolean[multiListItems.length];
                for (Alarm.Day day : getMathAlarm().getDays()) {
                    checkedItems[day.ordinal()] = true;
                }
                alert.setMultiChoiceItems(multiListItems, checkedItems, new OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, int which, boolean isChecked) {

                        Alarm.Day thisDay = Alarm.Day.values()[which];

                        if (isChecked) {
                            alarm.addDay(thisDay);
                        } else {
                            // Only remove the day if there are more than 1
                            // selected
                            if (alarm.getDays().length > 1) {
                                alarm.removeDay(thisDay);
                            } else {
                                // If the last day was unchecked, re-check
                                // it
                                ((AlertDialog) dialog).getListView().setItemChecked(which, true);
                            }
                        }

                    }
                });
                alert.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();

                    }
                });
                alert.show();
                break;
            case TIME:
                TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmPreferencesActivity.this,
                        new OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
                                Calendar newAlarmTime = Calendar.getInstance();
                                newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
                                newAlarmTime.set(Calendar.MINUTE, minutes);
                                newAlarmTime.set(Calendar.SECOND, 0);
                                alarm.setAlarmTime(newAlarmTime);
                                alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();
                            }
                        }, alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY),
                        alarm.getAlarmTime().get(Calendar.MINUTE), true);
                timePickerDialog.setTitle(alarmPreference.getTitle());
                timePickerDialog.show();
            default:
                break;
            }
        }
    });
}

From source file:io.github.data4all.activity.CameraActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "onCreate is called");

    // setting ignore warnings
    ignore = false;//from w  ww  . j  a va 2 s. c om
    // remove title and status bar
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    // It is important to call the super method after the window-features
    // are requested
    super.onCreate(savedInstanceState);

    shutterCallback = new ShutterCallback() {
        public void onShutter() {
            final Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATION_DURATION);
        }
    };
    mDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float x, float y) {
            if (x > MIN_SWIPE_VELOCITY) {
                CameraActivity.this.switchMode(currentMappingMode - 1);
                return true;
            } else if (x < -MIN_SWIPE_VELOCITY) {
                CameraActivity.this.switchMode(currentMappingMode + 1);
                return true;
            }
            return false;
        }
    });

    // The filter's action is BROADCAST_CAMERA
    IntentFilter mStatusIntentFilter = new IntentFilter(OrientationListener.BROADCAST_CAMERA);
    // Instantiates a new DownloadStateReceiver
    CalibrationReceiver mCalibrationReceiver = new CalibrationReceiver();
    // Registers the DownloadStateReceiver and its intent filters
    LocalBroadcastManager.getInstance(this).registerReceiver(mCalibrationReceiver, mStatusIntentFilter);

}

From source file:com.google.sample.cast.refplayer.chatting.MainActivity.java

public void setVibrate(int time) {
    Vibrator myVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
    myVibrator.vibrate(time);
}

From source file:com.marekscholtz.bluetify.utilities.BluetoothChatService.java

private void showNotification(Friend friend, ChatMessage chatMessage) {
    if (mHandler == null) {
        Intent clickIntent = new Intent(getApplicationContext(), ChatActivity.class);
        clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        clickIntent.putExtra("mac_address", friend.getMacAddress());
        PendingIntent clickPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, clickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.ic_logo_white_24dp).setPriority(Notification.PRIORITY_HIGH)
                .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
                .setContentTitle(friend.getName()).setContentIntent(clickPendingIntent).setAutoCancel(true);

        if (mSharedPreferences.getBoolean("notification_sound", false)) {
            notificationBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        }//  www. ja v  a 2s .  com

        if (mSharedPreferences.getBoolean("notification_vibration", false)) {
            notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
        }

        if (mSharedPreferences.getBoolean("notification_light", false)) {
            notificationBuilder.setLights(0xff0082fc, 1000, 1000);
        }

        if (!chatMessage.hasPicture()) {
            notificationBuilder.setContentText(new String(chatMessage.getContent()));
        } else {
            if (chatMessage.isSent()) {
                notificationBuilder.setContentText(
                        getApplicationContext().getResources().getString(R.string.you_sent_an_image) + ".");
            } else {
                notificationBuilder.setContentText(friend.getName() + " "
                        + getApplicationContext().getResources().getString(R.string.sent_you_an_image) + ".");
            }
        }

        if (friend.getProfilePhoto() != null) {
            byte[] profilePhotoBytes = friend.getProfilePhoto();
            Bitmap profilePhotoBitmap = BitmapFactory.decodeByteArray(friend.getProfilePhoto(), 0,
                    profilePhotoBytes.length);
            notificationBuilder.setLargeIcon(profilePhotoBitmap);
        }

        //TODO reply in notification
        //            if (android.os.Build.VERSION_CODES.N <= android.os.Build.VERSION.SDK_INT) {
        //                PendingIntent replyPendingIntent =
        //                        PendingIntent.getActivity(
        //                                getApplicationContext(),
        //                                0,
        //                                new Intent("REPLY"),
        //                                PendingIntent.FLAG_UPDATE_CURRENT
        //                        );
        //                RemoteInput remoteInput = new RemoteInput.Builder("message_text")
        //                        .setLabel(getString(R.string.write_a_message))
        //                        .build();
        //
        //                NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_send_white_24dp,
        //                        getString(R.string.reply), replyPendingIntent)
        //                        .addRemoteInput(remoteInput)
        //                        .build();
        //
        //                getApplicationContext().registerReceiver(new NotificationBroadcastReceiver(), new IntentFilter("REPLY"));
        //                notificationBuilder.addAction(action);
        //            }

        NotificationManager mNotificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, notificationBuilder.build());
    } else {
        Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(125);
    }
}

From source file:com.cybrosys.currency.CurrencyMain.java

public void vibrate() {
    Boolean isVibe = sharedPrefs.getBoolean("prefVibe", false);
    Vibrator vibe = (Vibrator) PalmCalcActivity.ctx.getSystemService(Context.VIBRATOR_SERVICE);
    if (isVibe) {
        vibe.vibrate(100);
    }//from ww w  .j av a  2 s . c  o m
}

From source file:eu.dirtyharry.androidopsiadmin.Main.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (vibrate) {
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(50);
    }//from   ww w  .  jav a  2 s  .co m
    switch (item.getItemId()) {
    case R.id.menu_preferences:
        Log.d("Barcode", "display preferences");

        new Functions().displayPreferences(Main.this);
        break;
    case R.id.menu_changelog:
        cl.getFullLogDialog().show();
        // case R.id.menu_close:
        break;
    case R.id.menu_donate:
        Intent browse = new Intent(Intent.ACTION_VIEW, Uri
                .parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LJAYM3ND7MUQE"));
        startActivity(browse);
        //         Toast.makeText(Main.this, "Spenden!", Toast.LENGTH_LONG).show();
        // case R.id.menu_close:
        break;
    case R.id.menu_about:
        Intent about = new Intent(Main.this, ShowAbout.class);
        startActivity(about);
        //         Toast.makeText(Main.this, "ber", Toast.LENGTH_LONG).show();
        // case R.id.menu_close:
        break;
    }

    return super.onOptionsItemSelected(item);
}

From source file:cl.gisred.android.RepartoActivity.java

private void alertFail() {
    ToneGenerator tgFail = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
    tgFail.startTone(ToneGenerator.TONE_CDMA_SOFT_ERROR_LITE, 200);

    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(1000);
}

From source file:com.b44t.ui.PasscodeActivity.java

private void onPasscodeError() {
    if (getParentActivity() == null) {
        return;//w w w  .j  a v  a  2  s  .  c  o m
    }
    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
    if (v != null) {
        v.vibrate(200);
    }
    AndroidUtilities.shakeView(titleTextView, 2, 0);
}

From source file:org.y20k.transistor.CollectionAdapter.java

private void handlePlayStopClick(int position) {
    // get current playback state
    loadAppState(mActivity);/*from  ww  w.j a v  a2 s  .co m*/

    if (mPlayback && mStationList.get(position).getPlaybackState()) {
        // stop player service using intent
        Intent intent = new Intent(mActivity, PlayerService.class);
        intent.setAction(TransistorKeys.ACTION_STOP);
        mActivity.startService(intent);
        LogHelper.v(LOG_TAG, "Stopping player service.");

        // remove playback flag from this station
        mPlayback = false;

        // inform user
        Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_long_press_playback_stopped),
                Toast.LENGTH_LONG).show();
    } else {
        // start player service using intent
        Intent intent = new Intent(mActivity, PlayerService.class);
        intent.setAction(TransistorKeys.ACTION_PLAY);
        intent.putExtra(TransistorKeys.EXTRA_STATION, mStationList.get(position));
        intent.putExtra(TransistorKeys.EXTRA_STATION_Position_ID, position);
        mActivity.startService(intent);
        LogHelper.v(LOG_TAG, "Starting player service.");

        // add playback flag to current station
        mPlayback = true;

        // inform user
        Toast.makeText(mActivity, mActivity.getString(R.string.toastmessage_long_press_playback_started),
                Toast.LENGTH_LONG).show();
    }

    // vibrate 50 milliseconds
    Vibrator v = (Vibrator) mActivity.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(50);

    // save app state
    saveAppState(mActivity);

}