How to Call Vibrator inside a Service in android

2019-08-07 00:58发布

问题:

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

回答1:

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 permission to AndroidManifest.xml:

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