如果从我的应用程序调用服务,我正在尝试运行 vibrator
。我正在从 Fragment
启动服务,但我不知道为什么振动器不工作在服务内部。我什至无法打印 Toast
。我的代码:
从 fragment 调用:
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"/>
最佳答案
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"/>
关于android - 如何在 android 服务中调用振动器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005055/