如何在Android中的服务中调用振动器 [英] How to Call Vibrator inside a Service in android
本文介绍了如何在Android中的服务中调用振动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我的应用程序调用了服务,我正在尝试运行振动器
。我正在从 Fragment
但我不知道为什么振动器无法在服务内部运行。我什至无法打印 Toast
。我的代码:
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:
从片段呼叫:
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;
}
}
我也尝试过这种方法,但是没有用:
I have also tried this and didn't work:
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
我在logcat中看到服务类中的每个函数都被调用,并且我还包含了权限。
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"/>
推荐答案
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中的服务中调用振动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文