android 拍照上传文件 原生定位

最近公司需要一个android拍照上传和定位功能的的单一功能页面,一开始选择ionic cordova angular的一套H5框架,但是遇到和上传文件报错的问题,bug找了一天没找到原因,怀疑是ionic版本问题,但是不重要了,不过有想继续研究问题的代码给你们,加油呀

git@github.com:tsxylhs/ionic-image-upload.git

因为赶的急临时抱佛脚,一天的时间将android入门然后写了这个Demo 希望大家共同学习,全栈就得有个全栈的样子你说对不,现在说正事

首先是定位, gps定位和网络定位,动态获取权限卡了一会,贴代码瞧瞧吧,写惯了golang 再写java感觉太臃肿了。。太臃肿了。。。。。臃肿。。。。了

     System.out.println("获取经纬度");
                showGPSContacts();

哈哈哈是是不是觉得我在逗你们,这个就是click里的方法了。实现showGpsContacts,根据多年菜逼的经验代码不要乱写,会更乱,放在类里调用就好了,上核心代码

  public void showGPSContacts() {
        LocationManager lm = (LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {//开了定位服务
            if (Build.VERSION.SDK_INT >= 23) { //判断是否为android6.0系统版本,如果是,需要动态添加权限
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {// 没有权限,申请权限。
                    ActivityCompat.requestPermissions(MainActivity.this, LOCATIONGPS,
                            BAIDU_READ_PHONE_STATE);
                } else {
                    getLocation();//getLocation为定位方法
                }
            } else {
                getLocation();//getLocation为定位方法
            }
        } else {
            Toast.makeText(MainActivity.this, "系统检测到未开启GPS定位服务,请开启", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, PRIVATE_CODE);
        }
    }

    /**
     * 获取具体位置的经纬度
     */
    private void getLocation() {
        // 获取位置管理服务
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) MainActivity.this.getSystemService(serviceName);
        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
        /**这段代码不需要深究,是locationManager.getLastKnownLocation(provider)自动生成的,不加会出错**/
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
        updateLocation(location);
    }

    /**
     * 获取到当前位置的经纬度
     *
     * @param location
     */
    private void updateLocation(Location location) {
        if (location != null) {
            lat = location.getLatitude();
             lng= location.getLongitude();
            locationSuccess = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示信息")//标题
                    .setMessage("获取定位成功!")//内容
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "获取定位成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }
                    }).setIcon(R.mipmap.ic_launcher).create();//图标
            locationSuccess.show();

            System.out.println("lat"+lat+":"+"location"+lng);
        } else {
            System.out.println("获取失败");
            locationError = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("定位失败")//标题
                    .setMessage("获取定位失败联系开发者:17615855621!")//内容
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "获取定位失败", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }
                    }).setIcon(R.mipmap.ic_launcher).create();//图标
            locationError.show();
        }
    }
}

其实我也是从网上找的例子,读一读,看一看 control c v 拿过来,这个就是拿来主义

AndroidManifest.xml 引入权限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

没有什么大毛病的话定位就走起了

接下来就是要拍照上传了这个说实话真耽误了一些功夫,没办法有拿来主义,就要有分享精神(哈哈)自吹自擂的话就不说了上代码

   //设置图片的保存路径,作为全局变量
                System.out.println("打开摄像头拍照");
                intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, PICK);

套路一样,逻辑分类些,就像是上海的垃圾分类,博主每天接收大妈的审问,我是什么垃圾,代码也一样,代码不分类也是和垃圾一样(丑呀)

重写

onActivityResult此方法
然后将
Bitmap 转换为文件 初步工作完成
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICK:
                if (resultCode == RESULT_OK) {
                    //将拍摄的照片显示出来
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    base64ImageData = bitmapToBase64(bitmap);
                    imageView.setImageBitmap(bitmap);
                    file= compressImage(bitmap);
                    // 拍照完成并且显示完成
                    // todo 上传图片和位置信息

                }
                break;
            default:
                break;
        }
    }
   //转换文件
    public File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file;
    }

上传有点乱将就吧,天不早该睡觉了,有些业务上的逻辑请忽略

  System.out.println("上传图片");
                address = editTextAddress.getText().toString();
                deviceId = editTextDeviceId.getText().toString();
                System.out.println("address:" + address);


                if (address==""||deviceId==""||lng==0.0||lat==0.0) {

                    alertDialog1 = new AlertDialog.Builder(MainActivity.this)
                            .setTitle("错误")//标题
                            .setMessage("内容未完善!")//内容
                            .setPositiveButton("重新完善内容", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(MainActivity.this, "重新完善内容", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                }
                            }).setIcon(R.mipmap.ic_launcher).create();//图标
                    alertDialog1.show();


                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
                            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
                            RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                                    .addFormDataPart("file", deviceId, fileBody)
                                    .addFormDataPart("address", address)
                                    .addFormDataPart("deviceId", deviceId)
                                    .addFormDataPart("latlong", lat + ":" + lng).build();
                            Request request = new Request.Builder().url(url).post(requestBody).build();
                            okHttpClient.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                    Log.i("response:", e.toString());
                                    Looper.prepare();
                                  AlertFailure= new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("上传失败")//标题
                                            .setMessage("上传失败请联系开发者:17615855621!")//内容
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                                                    dialog.dismiss();
                                                }
                                            }).setIcon(R.mipmap.ic_launcher).create();//图标
                                    AlertFailure.show();

                                    Looper.loop();
                                    System.out.println(e.getMessage());
                                }

                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    Log.i("response:", response.toString());
                                    Looper.prepare();
                                   AlerDialogsuccess= new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("上传成功")//标题
                                            .setMessage("上传成功!")//内容
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                                    dialog.dismiss();
                                                }
                                            }).setIcon(R.mipmap.ic_launcher).create();//图标
                                    AlerDialogsuccess.show();
                                    Looper.loop();
                                    System.out.println("上传成功");
                                }
                            });


                        }
                    }).start();
                }

AndroidManifest.xml 引入权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

至此便大获全胜。本教程只适合1天android工龄人查看,大神请绕路行驶,以免发生车祸

页面要不要贴。。。。。不贴了吧都是拖出来的毫无美感可言

最后源代码来啦请注意查收:

https://github.com/tsxylhs/android-image-upload

谢谢,欢迎留言交流

 

posted @ 2019-07-08 23:57  菜鸟的进击  阅读(1595)  评论(0编辑  收藏  举报