How to call a vibrator inside a service in android

I am trying to start vibrator if a service is being called from my application. I start the service from Fragment , but I do not know why the vibrator does not work inside the service. I could not even print Toast . My code is:

Call from fragment:

 Intent buzz= new Intent(getActivity(),LocBuzzService.class); getActivity().startService(buzz); 

Class of service:

 public class LocBuzzService extends Service { private static final String TAG = "HelloService"; private boolean isRunning = false; public Vibrator vibrator; @Override public void onCreate() { Log.i(TAG, "Service onCreate"); isRunning = true; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "Service onStartCommand"); new Thread(new Runnable() { @Override public void run() { try{ Log.i(TAG, "I am in thread"); Toast.makeText(getApplicationContext(),"I am here",Toast.LENGTH_LONG).show(); vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(3000); vibrator.cancel(); }catch (Exception e){ } stopSelf(); } }).start(); return Service.START_STICKY; } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "Service onBind"); return null; } @Override public void onDestroy() { Log.i(TAG, "Service onDestroy"); isRunning = false; } } 

I tried this too and didn't work:

  vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 

I saw in logcat that all functions are called inside the service class, and I also included this permission.

 <uses-permission android:name="android.permission.VIBRATE"/> 
+1
source share
1 answer
 package com.mani.smsdetect; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.Vibrator; import android.support.annotation.Nullable; public class SampleService extends Service{ Vibrator vibrator; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { vibrator.vibrate(2000); return super.onStartCommand(intent, flags, startId); } } 

Add vibrator resolution to AndroidManifest.xml :

 <uses-permission android:name="android.permission.VIBRATE"/> 
+2
source

All Articles