我正在开发一款能够在摇动手机后执行功能的应用。为此,我创建了一个名为ShakeListener的类。我的应用程序完全像我打开时的应用程序。当我打开应用程序并按下后退按钮并转到我的主屏幕并摇动手机时,它会打开闪光灯(就像它应该的那样)但是当我再次打开应用程序时它会崩溃。我不知道为什么会发生这种情况
我的主要活动是
public class MainActivity extends ActionBarActivity {
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn && mShaker != null ) {
getCamera();
turnOnFlash();
} else {
turnOffFlash();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
}
private void getCamera() {
// TODO Auto-generated method stub
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} }
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
@Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.action_settings:
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
break;
case R.id.about:
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
break;
}
return true;
}
}
我的logcat显示
08-23 04:31:53.205:D / ShakeListener(11990):调用ShakeListener ----> 08-23 04:31:53.207:D / ShakeListener(11990):调用ShakeListener setOnShakeListener ----> 08-23 04:31:53.312:D / AndroidRuntime(11990):关闭虚拟机 08-23 04:31:53.314:E / AndroidRuntime(11990):致命异常:主要 08-23 04:31:53.314:E / AndroidRuntime(11990):进程:com.shakylight,PID:11990 08-23 04:31:53.314:E / AndroidRuntime(11990):java.lang.ClassCastException:android.graphics.drawable.BitmapDrawable无法强制转换为android.graphics.drawable.AnimationDrawable 08-23 04:31:53.314:E / AndroidRuntime(11990):at com.shakylight.MainActivity $ 4.run(MainActivity.java:145) 08-23 04:31:53.314:E / AndroidRuntime(11990):在android.os.Handler.handleCallback(Handler.java:739) 08-23 04:31:53.314:E / AndroidRuntime(11990):在android.os.Handler.dispatchMessage(Handler.java:95) 08-23 04:31:53.314:E / AndroidRuntime(11990):在android.os.Looper.loop(Looper.java:135) 08-23 04:31:53.314:E / AndroidRuntime(11990):在android.app.ActivityThread.main(ActivityThread.java:5254) 08-23 04:31:53.314:E / AndroidRuntime(11990):at java.lang.reflect.Method.invoke(Native Method) 08-23 04:31:53.314:E / AndroidRuntime(11990):at java.lang.reflect.Method.invoke(Method.java:372) 08-23 04:31:53.314:E / AndroidRuntime(11990):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903) 08-23 04:31:53.314:E / AndroidRuntime(11990):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
答案 0 :(得分:4)
当您投射时,问题似乎出现在以下行:
AnimationDrawable frameAnimation = (AnimationDrawable) anime.getDrawable();
您在anime.setImageResource()
上使用ImageView
来设置您的drawable。请尝试使用anime.setImageDrawable(getResource().getDrawable(R.drawable. anim);
并查看错误是否仍然存在。
答案 1 :(得分:1)
免责声明:我无法测试我建议您在这里尝试的内容,但它可能会正常工作。无论如何,您可以在评论中告诉我。
所以错误来自这一行:
var handleRequest = function(context, funcToExec) {
context.response.setHeader('Access-Control-Allow-Origin', '*');
var requestMethod = context.request.method.toUpperCase();
if (requestMethod === "OPTIONS" ) {
//TODO: Uncomment this!
context.response.setHeader( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' );
context.response.setHeader('Access-Control-Allow-Methods', 'POST, PUT, GET, DELETE, OPTIONS');
context.response.end('Set OPTIONS.');
return true;
} else {
//Get the data from the function
var data = funcToExec(context);
//Send it back to the client
context.response.setHeader('Content-Type', 'application/json');
context.response.statusCode = 200;
context.response.end(JSON.stringify(data));
}
};
Router.route(/* route here */, function() {
handleRequest(this, function(c) {
//Extract context query parameters, do some work and return the data
//...
var data = {key: 'key', value: 'data'};
return data;
});
}, {where: server});
我不是专家,文档也无济于事。 Android文档示例如下:(请参阅此处:http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html)
{
"cmd": [
"meteor",
"--port",
"$PORT"
],
"info": "Meteor",
"working_dir": "$project_path",
"env": {
"NODE_OPTIONS": "${debug?--debug-brk=<PORT>}",
"ROOT_URL": "https://$C9_HOSTNAME",
"BIND_IP": "$IP"
},
"debugger": "v8",
"debugport": <PORT>
}
然而,彻底搜索SO(这里= "Class Cast Exception" when trying to set image frames to background)给了我这个解决方案显然要执行以下操作(与文档逻辑相反):
AnimationDrawable frameAnimation = (AnimationDrawable) anime.getDrawable();