I am trying to run the vibrator
if service is called from my app.I am starting the service from Fragment
but i don't know why vibrator is not working inside the service.I couldn't even print the Toast
.My code:
Calling from Fragment:
Intent buzz= new Intent(getActivity(),LocBuzzService.class);
getActivity().startService(buzz);
Service class:
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 have also tried this and didn't work:
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
I saw in logcat that every function inside the service class are called and i have also included the permission.
<uses-permission android:name="android.permission.VIBRATE"/>
Add vibrator permission to
AndroidManifest.xml
: