【发布时间】:2015-05-02 17:01:41
【问题描述】:
如果从我的应用程序调用服务,我正在尝试运行vibrator。我正在从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"/>
【问题讨论】:
-
catch块中是否发生异常? -
为什么你在调用 vibrate() 后立即取消它?
-
我想运行振动器3秒然后取消它
-
删除该行。对 vibrate(3000) 的调用不会阻塞,因此它会导致振动在它开始之前被取消。震动3000后“结束”,无需取消
-
除此之外,永远不要在不记录的情况下捕获异常,尤其是在调试应用程序时。
标签: android android-fragments service android-vibration