使用振动器时应用程序崩溃,即使hasVibrator()返回true
问题描述:
我正在研究一个涉及振动的小应用程序,每当调用vibrate()
函数时,应用程序都会崩溃。堆栈跟踪链接回到vibrator.vibrate()行,文本为“Vibrator:Failed to vibrate。”。振动器。还有一些DeadObjectExceptions
和RuntimeExceptions
,它们都链接到Android类。这只发生在一些手机上,其他手机完美运作。使用振动器时应用程序崩溃,即使hasVibrator()返回true
hasVibrator()
返回true
,和振动器对象是非空的,手机有一个振动器,所以我不知道什么是错的。也许我在振动器物体创建后过早振动,或者我在onCreate()
方法中过早创建振动器物体?
这里是我使用的vibrate()
方法的部分代码:
//vibrate only if exists
if (vibrating)
{
long[] pattern = {0, power, target - power};
try
{
vibrator.vibrate(pattern, 0);
}
catch (Exception e)
{
vibrating = false;
}
}
答
假设你正在使用getSystemService你可以期望得到的服务或NULL,如果类是不支持的系统服务。
现在,既然你说你在不同的设备上得到了某些例外,你可以捕获这些例外。
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if(vibrator != null)
{
try
{
long[] pattern = { 0, 200, 500 };
vibrator.vibrate(pattern, 0);
}
catch(DeadObjectExceptions e)
{
e.printStackTrace();
}
}
+0
我已经在检查一个例外(我知道这不是一个好习惯,它只是用于测试),但它仍然崩溃。 – AtlasShrugging
答
添加震动许可,您的AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE"/>
你介意张贴满异常,代码?谢谢。 –
@NewtronLabs我现在无法访问其中一个失败的电话,但是我会在明天再添加它。 – AtlasShrugging