我有一个简单的Flashlight应用程序,它有一个小部件,它在安装后很长一段时间内工作正常,但随后小部件停止响应,它只是不响应点击而且不会引发任何错误。我可能在我的代码中做了一些错误或非理性的事情,因为我是小部件的新手,但我似乎无法确定它们并理解导致问题的原因。
这是我的代码:
public class MyAppWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Intent receiver = new Intent(context, MyAppWidgetReceiver.class);
receiver.setAction("COM_FLASHLIGHT");
receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver,0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
views.setOnClickPendingIntent(R.id.imageButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
}
public class MyAppWidgetReceiver extends BroadcastReceiver {
public static boolean isActive = false;
public static Flash flash = new Flash();
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
if(isActive){
isActive = false;
flash.off();
flash.close();
views.setImageViewResource(R.id.imageButton, R.drawable.pers_off);
}else{
isActive = true;
flash.open();
flash.on();
views.setImageViewResource(R.id.imageButton, R.drawable.pers_on);
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context, MyAppWidget.class), views);
}
}
我的Flash课程,以防万一:
public class Flash {
private Camera camera = null;
private Camera.Parameters cameraParameters;
private String previousFlashMode = null;
public synchronized void open() {
camera = Camera.open();
if (camera != null) {
cameraParameters = camera.getParameters();
previousFlashMode = cameraParameters.getFlashMode();
}
if (previousFlashMode == null) {
// could be null if no flash, i.e. emulator
previousFlashMode = Camera.Parameters.FLASH_MODE_OFF;
}
}
public synchronized void close() {
if (camera != null) {
cameraParameters.setFlashMode(previousFlashMode);
camera.setParameters(cameraParameters);
camera.release();
camera = null;
}
}
public synchronized void on() {
if (camera != null) {
cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(cameraParameters);
camera.startPreview();
}
}
public synchronized void off() {
if (camera != null) {
camera.stopPreview();
cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(cameraParameters);
}
}
public Camera getCamera(){
return camera;
}
}