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"/>
source share