在Android中获取拍摄照片的位置数据 [英] Getting location data for a taken photo in Android

查看:113
本文介绍了在Android中获取拍摄照片的位置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在Android中获取位置(拍照时的GPS /网络)。
欢迎任何建议和代码示例。直到现在我还没有使用位置服务,我尝试了很多方法,但是我无法完成它。



以下是我的图像捕获活动:

  public class ImageCaptureActivity extends Activity {

//活动请求代码
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
上下文上下文= null;

//存储捕获图像的目录名称
private static final String IMAGE_DIRECTORY_NAME =Asisoft;

私人Uri fileUri; //文件URL存储图像

私人ImageView imgPreview;
私人按钮btnCapturePicture;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.image_capture);

context = getApplicationContext();
imgPreview =(ImageView)findViewById(R.id.imgPreview);
btnCapturePicture =(Button)findViewById(R.id.btnCapturePicture);
$ b / **
*捕获图像按钮点击事件
* * /
btnCapturePicture.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v){
//捕获图片
captureImage();
}
});


关闭相机后会调用接收活动结果方法

  @Override 
protected void onActivityResult(int requestCode,int resultCode,Intent data){
// if结果是捕获图像
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
if(resultCode == RESULT_OK){
//成功捕获图像
//在图像视图中显示它
previewCapturedImage();
$ b $ else if(resultCode == RESULT_CANCELED){
//用户取消图像捕获
Toast.makeText(getApplicationContext(),
已取消,Toast。 LENGTH_SHORT)
.show();
} else {
//未能捕获图像
Toast.makeText(getApplicationContext(),
Error!,Toast.LENGTH_SHORT)
.show() ;
}
}

}

存储文件url,因为从相机应用返回后它将为空

  @Override 
保护无效onSaveInstanceState(Bundle outState ){
super.onSaveInstanceState(outState);

//将文件url保存在bundle中,因为它在scren方向上将为null
//更改
outState.putParcelable(file_uri,fileUri);

$ / code>

这里我再次恢复了fileUri

  @Override 
保护无效onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);

//获取文件url
fileUri = savedInstanceState.getParcelable(file_uri);
}

启动相机的方法

  private void captureImage(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);

//启动图像捕捉Intent
startActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

$ b

创建文件uri来存储图像/视频

  public Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));

$ b $ * b $ b *返回图片/视频
* /
私有静态文件getOutputMediaFile(int type){

//外部sdcard位置
文件mediaStorageDir =新文件(
环境
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);

//创建存储目录如果不存在
if(!mediaStorageDir.exists()){
if(!mediaStorageDir.mkdirs()){
Log.d(IMAGE_DIRECTORY_NAME,Fisierul
+ IMAGE_DIRECTORY_NAME +nu a fost creat);
返回null;



//创建一个媒体文件名
String timeStamp = new SimpleDateFormat(yyyyMMdd_HHmmss,
Locale.getDefault())。格式(新日期());
文件mediaFileName;
if(type == MEDIA_TYPE_IMAGE){
mediaFileName = new File(mediaStorageDir.getPath()+ File.separator
+IMG_+ timeStamp +.jpg);
} else {
return null;
}

return mediaFileName;



$ b

显示图像从路径到ImageView

  private void previewCapturedImage(){
try {
imgPreview.setVisibility(View.VISIBLE);

// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();

//缩小图像的尺寸OutOfMemory Exception对于较大的
//图像
options.inSampleSize = 8;

最终位图位图= BitmapFactory.decodeFile(fileUri.getPath(),
options);

imgPreview.setImageBitmap(bitmap);

} catch(NullPointerException e){
e.printStackTrace();
}
}


}



private final Context mContext;

//标记GPS状态
boolean isGPSEnabled = false;

//标记网络状态
布尔isNetworkEnabled = false;

//标记GPS状态
boolean canGetLocation = false;

位置位置; //位置
双纬度; //纬度
双经度; // Longitude

//改变的最小距离以米为单位的更新
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10米

//以毫秒为单位的最小更新时间间隔
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟

//声明位置管理器
受保护的LocationManager locationManager;

公共GPSTracker(上下文环境){
this.mContext = context;
getLocation();


public Location getLocation(){
try {
locationManager =(LocationManager)mContext
.getSystemService(LOCATION_SERVICE);

//获取GPS状态
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

//获取网络状态
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!isGPSEnabled&&!isNetworkEnabled){
//没有启用网络提供程序
} else {
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(网络,网络);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();


$ b //如果启用了GPS,使用GPS服务得到纬度/经度
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(已启用GPS,已启用GPS);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();





catch(例外e){
e.printStackTrace();
}

返回地点;
}


/ **
*停止使用GPS监听器
*调用此函数将停止在您的应用中使用GPS。
* /
public void stopUsingGPS(){
if(locationManager!= null){
locationManager.removeUpdates(GPSTracker.this);



$ b / **
*函数获得纬度
* * /
public double getLatitude() {
if(location!= null){
latitude = location.getLatitude();
}

//返回纬度
返回纬度;


$ b / **
*函数获得经度
* * /
public double getLongitude(){
if(location!= null){
longitude = location.getLongitude();
}

//返回经度
返回经度;
}

/ **
*支持GPS / Wi-Fi的功能
* @return布尔
* * /
public boolean canGetLocation(){
return this.canGetLocation;
}


/ **
*显示设置警报对话框的功能。
*按下设置按钮后,它将启动设置选项。
* * /
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

//设置对话框标题
alertDialog.setTitle(GPS is settings);

//设置对话框消息
alertDialog.setMessage(GPS未启用,是否要进入设置菜单?);

//按下设置按钮。
alertDialog.setPositiveButton(Settings,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

//按下取消按钮
alertDialog.setNegativeButton(取消,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
dialog.cancel();
}
});

//显示提示信息
alertDialog.show();



@Override
public void onLocationChanged(位置位置){
}


@Override
public void onProviderDisabled(String provider){
}


@Override
public void onProviderEnabled(String provider){
}


@Override
public void onStatusChanged(String provider,int status,Bundle extras){
}


@Override
public IBinder onBind(意向arg0){
返回null;
}

}

当你在 ActivityforResult()中使用此代码来获取位置
时,可以像这样

  GPSTracker gps; 
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
//如果结果是捕获图像
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
gps =新GPSTracker(AndroidGPSTrackingActivity.this);

if(resultCode == RESULT_OK)
{
previewCapturedImage();
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();

// \\\
是换行
Toast.makeText(getApplicationContext(),您的位置是 - \\\
Lat:+ latitude +\\\
Long:+ longitude ,Toast.LENGTH_LONG).show();
} else {
//无法获取位置。
// GPS或网络未启用。
//要求用户在设置中启用GPS /网络。


$ b} else if(resultCode == RESULT_CANCELED){
//用户取消图像捕获
Toast.makeText(getApplicationContext(),
已取消,Toast.LENGTH_SHORT)
.show();
} else {
//未能捕获图像
Toast.makeText(getApplicationContext(),
Error!,Toast.LENGTH_SHORT)
.show() ;
}
}

}


I don't know how to get the location (GPS/Network when taking a photo) in Android. Any suggestion and code samples are welcomed. I haven't used until now the Location services, I have tried in many ways but I can't get it to work.

Here is my image capturing activity:

public class ImageCaptureActivity extends Activity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
Context context = null;

// directory name to store captured images
private static final String IMAGE_DIRECTORY_NAME = "Asisoft";

private Uri fileUri; // file url to store image

private ImageView imgPreview;
private Button btnCapturePicture;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image_capture);

    context = getApplicationContext();
    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);

    /**
     * Capture image button click event
     * */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });

}

Receiving activity result method will be called after closing the camera

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // successfully captured the image
            // display it in image view
            previewCapturedImage();

        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "Cancelled", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Error!", Toast.LENGTH_SHORT)
                    .show();
        }
    }

}

Here we store the file url as it will be null after returning from camera app

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on scren orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

Here I restore the fileUri again

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}

Method to fire up camera

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}

Creating file uri to store image/video

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/*
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Fisierul "
                    + IMAGE_DIRECTORY_NAME + " nu a fost creat");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFileName;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFileName = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFileName;
}

Display image from a path to ImageView

private void previewCapturedImage() {
    try {
        imgPreview.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        imgPreview.setImageBitmap(bitmap);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}


}

解决方案

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// Flag for GPS status
boolean isGPSEnabled = false;

// Flag for network status
boolean isNetworkEnabled = false;

// Flag for GPS status
boolean canGetLocation = false;

Location location; // Location
double latitude; // Latitude
double longitude; // Longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // Getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // Getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // No network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // If GPS enabled, get latitude/longitude using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}


/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app.
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}


/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}


/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/Wi-Fi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}


/**
 * Function to show settings alert dialog.
 * On pressing the Settings button it will launch Settings Options.
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing the Settings button.
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // On pressing the cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}


@Override
public void onLocationChanged(Location location) {
}


@Override
public void onProviderDisabled(String provider) {
}


@Override
public void onProviderEnabled(String provider) {
}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}


@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

when u take the picture in ActivityforResult() use this code to get the location like this

  GPSTracker gps;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
          gps = new GPSTracker(AndroidGPSTrackingActivity.this);

            if (resultCode == RESULT_OK) 
             {
                     previewCapturedImage();
                     if(gps.canGetLocation())
                    {
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                } else {
                    // Can't get location.
                    // GPS or network is not enabled.
                    // Ask user to enable GPS/network in settings.

                }

            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "Cancelled", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Error!", Toast.LENGTH_SHORT)
                        .show();
            }
        }

    }

这篇关于在Android中获取拍摄照片的位置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆