Pergunta

I have a little problem.

My app must vibrate when on button is pressed, all work fine in my Samsung S3 (API 17) but on my S2 (API 15) this is not working.

The code:

   <uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.VIBRATE"/>

Main

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    Vibrator x = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    x.cancel();
    backgroundVibrate = 0;
    //final ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton1);
    setContentView(R.layout.activity_fullscreen);

    Button fast1 = (Button) findViewById(R.id.fast1);
    fast1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            long[] pattern = { 0, 100, 300 };
            vibrate(pattern, false);
        }
    });
   public void vibrate(long[] pattern, boolean stop)
{
    // Get instance of Vibrator from current Context
    Vibrator x = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    if (stop == false)
    {
        x.vibrate(pattern, 0);
        currentVibrate = true;
        System.out.println("vibrate ON");
    }
    if (stop == true)
    {
        x.cancel();
        currentVibrate = false;
    }

}

Someone have an idea?

thanks

Foi útil?

Solução

The simple way to do the job is to use Haptic Feedback

Button fast1 = (Button) findViewById(R.id.fast1);
fast1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
    }
});

The good part with this is you do not need to set a permission in the AndroidManifest. Please note you need enable Haptic Feedback as global. check it from http://developer.android.com/reference/android/view/HapticFeedbackConstants.html .

You can simply use following code to enable Haptic Feedback for your application.

Settings.System.putInt(getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);

don't forget to add the following permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

Outras dicas

Those vibrate durations are really short. I'd suggest, as a test, that you stick a zero at the end of each to see whether the vibrate actually works to discount the issue of the code functioning properly.

Then, I suppose you'll just have to have to set a duration that is acceptable on all hardware (since different hardware will have varying levels of sensitivity, for want of a better word).

All is good with my initial solution.

The problem is from Samsung S2 Settings....

Thanks for your help

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top