摇动手机后,我正在开发执行功能的应用程序。为此,我创建了一个名为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):关闭VM
  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(本机方法)
  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)

最佳答案

免责声明:我无法测试我建议您在此处尝试的内容,但可能会很好。无论如何,您可以在评论中让我知道。

因此,错误来自以下行:

AnimationDrawable frameAnimation = (AnimationDrawable) anime.getDrawable();


我不是专家,文档也无济于事。 Android文档示例如下:(请参见此处:http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();


但是,对SO(here = "Class Cast Exception" when trying to set image frames to background)进行了彻底的搜索后,我发现解决方案显然可以执行以下操作(与文档的逻辑相反):

Drawable drawable = getResources().getDrawable(R.drawable.<your_animation_xml_file_name>)

10-04 14:52