3

我正在尝试vibrator从我的应用程序调用 if 服务。我正在启动服务,Fragment但我不知道为什么振动器在服务内部不起作用。我什至无法打印。我的Toast代码:

从片段调用:

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

服务等级:

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;
    }
}

我也试过这个,但没有奏效:

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

我在 logcat 中看到服务类中的每个函数都被调用,并且我还包含了权限。

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

1 回答 1

3
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);

    }


}

将振动器权限添加到AndroidManifest.xml

<uses-permission android:name="android.permission.VIBRATE"/>
于 2016-04-12T06:05:33.277 回答