我正在尝试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"/>