我制作了基于标签的应用。有三个选项卡。其中一个标签用于相机。因此,当我按下相机标签时,它会打开相机活动,以便我可以拍照。直到这里它工作正常。当我拍照时,那张照片会在ImageView中显示出来。 从此处按下任何其他选项卡,然后按相机标签,然后相机活动无法启动。它会一直向我显示ImageView上的上一张图像。我想要的是每当用户点击相机标签时,它应该打开相机活动。 如何实现此效果?
这是我的代码。在os oncreate方法下面是相机活动。因此,当按下相机选项卡时,它会打开此活动。
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
更新
我这样做但仍然是同样的问题
boolean flag = true;
@Override
protected void onResume() {
super.onResume();
//flag = true;
if(flag) {
openCamera();
flag = false;
}
}
修改
在跟随Imran的回答后,我的代码现在看起来像这样。我还在添加其他代码。但是这段代码仍然不起作用。
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;
String largeImagePath;
int serverResponseCode = 0;
public static boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
//flag = getIntent().getExtras().getBoolean("flag");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
//openCamera();
if(flag ==true)
openCamera();
}
@Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
flag = false;
if(resultCode == RESULT_OK) {
//set image taken from camera on ImageView
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
try {
myCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
File f = new File("" + largeImagePath);
photoName = f.getName();
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Upload().execute(largeImagePath, globalUID, photoName);
}
});
} finally {
myCursor.close();
}
}
}
}
这是我的标签活动代码
public class DashboardActivity extends TabActivity {
UserFunctions userFunctions;
public String globalUID;
DatabaseHandler db;
boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
db = new DatabaseHandler(getApplicationContext());
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
//globalUID = getIntent().getExtras().getString("globalUID");
HashMap<String, String> data = db.getUserDetails();
globalUID = data.get("uid");
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
//Home
intent = new Intent(this, Home.class);
intent.putExtra("globalUID", globalUID);
spec = tabHost.newTabSpec("home").setIndicator("", res.getDrawable(R.drawable.home_icon)).setContent(intent);
tabHost.addTab(spec);
//Camera
intent = new Intent(this, Camera.class);
intent.putExtra("globalUID", globalUID);
//intent.putExtra("flag", flag);
spec = tabHost.newTabSpec("camera").setIndicator("", res.getDrawable(R.drawable.camera_icon)).setContent(intent);
tabHost.addTab(spec);
//Albums
intent = new Intent(this, Albums.class);
intent.putExtra("globalUID", globalUID);
spec = tabHost.newTabSpec("albums").setIndicator("", res.getDrawable(R.drawable.albums_icon)).setContent(intent);
tabHost.addTab(spec);
//tabHost.setCurrentTab(1);
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
}
这是我的整个相机活动
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;
String largeImagePath;
int serverResponseCode = 0;
public static boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
//flag = getIntent().getExtras().getBoolean("flag");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
//openCamera();
//if(flag ==true)
openCamera();
}
/*
@Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}*/
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
flag = false;
if(resultCode == RESULT_OK) {
//set image taken from camera on ImageView
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
try {
myCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
File f = new File("" + largeImagePath);
photoName = f.getName();
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Upload().execute(largeImagePath, globalUID, photoName);
}
});
} finally {
myCursor.close();
}
}
}
public class Upload extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String success = "false";
Bitmap bitmapOrg = setImageToImageView(largeImagePath);//BitmapFactory.decodeFile(largeImagePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, 0);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("imageName", photoName));
nameValuePairs.add(new BasicNameValuePair("uid", globalUID));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.info/android/fileupload.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(response != null) {
success = "true";
}
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
dialog.dismiss();
return success;
}
protected void onProgressUpdate(Integer...progress) {
}
protected void onPostExecute(String f) {
Toast.makeText(getApplicationContext(), "File uploaded", Toast.LENGTH_LONG).show();
}
}
public Bitmap setImageToImageView(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
public boolean fileData(String guid, String photoName) {
Toast.makeText(getApplicationContext(), photoName, Toast.LENGTH_LONG).show();
JSONObject json = userFunctions.uploadFileData(guid, photoName);
try {
if(Integer.parseInt(json.getString("success")) != 1) {
Toast.makeText(getApplicationContext(), json.getInt("error_msg"), Toast.LENGTH_LONG).show();
//register_error.setText(json.getString("error_msg"));
return false;
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
答案 0 :(得分:0)
这是因为当您在标签之间切换时,您的活动不会再次调用onCreate。
尝试将呼叫转移到openCamera();进入onResume方法,它应该没问题。
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
}
protectd void onResume(){
super.onResume();
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
答案 1 :(得分:0)
Activity
中的每个TabHost
仅为了效率而调用onCreate()
一次。这就是openCamera()
不会一次又一次被调用的原因。
为了解决这个问题,您可以在父Activity
中实现并注册OnTabChangeListener
,您可以在其中捕获单击的标签并执行任何所需的操作。
希望这有帮助!
答案 2 :(得分:0)
在您的活动中添加onResume()
并调用openCamera();从onResume()也可以:
public static boolean flag = true;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
if(flag ==true)
openCamera();
}
@Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}
并在onActivityResut()
flag =false;
或在tabclick上
YourflagActivity.flag=true;