有人可以解释一下为什么我的代码崩溃了......
Camera.Parameters p = camera.getParameters(); //crashing line
代码是
package it.elec29a.ultra.flashlight;
import java.io.IOException;
import java.util.Random;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class MyWidgetProvider extends AppWidgetProvider {
private Camera camera=null;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return;
}
if(camera!=null) camera=Camera.open();
// Get all ids
ComponentName thisWidget = new ComponentName(context,
MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
Log.d("In Widget ",""+widgetId);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
// Register an onClickListener
Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonwidget, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
Camera.Parameters p = camera.getParameters(); //crashing line
if(true) return; //for debug exit
String flashMode = p.getFlashMode();
if(flashMode == null) {
//DO something, if it has no value
} else if(flashMode.equals(Camera.Parameters.FLASH_MODE_OFF)) {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
} else if(flashMode.equals(Camera.Parameters.FLASH_MODE_TORCH)) {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
}
}
}
有人可以帮我解决这个问题...... thx
答案 0 :(得分:1)
您的代码中至少存在两个明显的问题。
你的专栏:
if(camera!=null) camera=Camera.open();
...初始化Camera
对象,如果它不是null
(听起来很奇怪 - 可能永远不会被初始化)。
但是以下所有代码,包括:
Camera.Parameters p = camera.getParameters();
... 不取决于camera != null
的事实,因此它可能引用了null
指针。
因此你可能会抛出一个NullPointerException
(我说“可能”因为你没有发布堆栈跟踪)。
我会改变你的代码:
// removed if(camera!=null)
camera = Camera.open();
// checking "camera" is not null
if (camera != null) { // using curly brackets, comes very handy sometimes :D
// ... the rest of the code
}