zoukankan      html  css  js  c++  java
  • android 学习

    今天完成了前两个阶段

    经过一周的学习,已经可以完成这一款APP的开发

    主要功能代码

    package com.example.myapplication2;
    
    import android.Manifest;
    import android.annotation.TargetApi;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import androidx.annotation.RequiresApi;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    
    import com.baidu.location.BDAbstractLocationListener;
    import com.baidu.location.BDLocation;
    import com.baidu.mapapi.SDKInitializer;
    
    import java.io.File;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    
    import jxl.Workbook;
    import jxl.write.Label;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    import jxl.write.WriteException;
    import jxl.write.biff.RowsExceededException;
    
    
    public class MainActivity extends Activity implements View.OnClickListener {
        private int REQUEST_PERMISSION_CODE = 1000;//表格
        private final int SDK_PERMISSION_REQUEST =127;
        private LocationService locationService;
        private EditText etTime;
        private SharedPreferences sharedPreferences;
        private Button startLocation;
        private Button putDatabase;
        private EditText etName;
        private EditText etTemper;
        private EditText mm;
        private EditText date;
        private EditText etDate;
        private EditText etPosition;
        private DatabaseHelper dbHelper;
        private DatabaseHelper2 dbHelper2;
        private Button reacherDatabase;
        String str="";
        String name="";
        String pp="";
    
        String phone="";
        String cla="";
        String xuehao="";
    
        private AlertDialog alertDialog;
        private AlertDialog mDialog;
    
        String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写限权
    
        private String filePath = "test3";//文件路径
        File file;
    
        private EditText t1;
        private EditText t2;
        private EditText t3;
        private EditText t4;
    
        private CheckBox a;
        private CheckBox b;
        private CheckBox c;
        private CheckBox d;
        private CheckBox e;
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            SDKInitializer.initialize(getApplicationContext());
            setContentView(R.layout.activity_main);
    
            Bundle bundle = getIntent().getExtras();
            name= bundle.getString("name");
            cla= bundle.getString("cla");
            phone= bundle.getString("phone");
            xuehao= bundle.getString("xuehao");
    
    
            a= (CheckBox) findViewById(R.id.check1);
            b = (CheckBox) findViewById(R.id.check2);
            c = (CheckBox) findViewById(R.id.check3);
            d = (CheckBox) findViewById(R.id.check4);
            e = (CheckBox) findViewById(R.id.check5);
    
    
            t1=findViewById(R.id.et31);
            t2=findViewById(R.id.et32);
            t3=findViewById(R.id.et33);
            t4=findViewById(R.id.et34);
    
            t1.setVisibility(View.GONE);
            t2.setVisibility(View.GONE);
            t3.setVisibility(View.GONE);
            t4.setVisibility(View.GONE);
    
    
    
    
    
            date=findViewById(R.id.date);
            date.setText(getDate());
            getPersimmions();
            dbHelper = new DatabaseHelper(this, "TTList3.db",null,3);
            dbHelper.getWritableDatabase();
            etName=findViewById(R.id.et1);
            etTemper=findViewById(R.id.et2);
            etDate=findViewById(R.id.date);
            etPosition=findViewById(R.id.et3);
            putDatabase = findViewById(R.id.but1);
    
            startLocation=findViewById(R.id.dingwei);
            initData();
            initUI();
            initUI2();
    
    
        }
    
    
    
        private void initUI2() {
            findViewById(R.id.but2).setOnClickListener(this);
            findViewById(R.id.button3).setOnClickListener(this);
            findViewById(R.id.button4).setOnClickListener(this);
            findViewById(R.id.button7).setOnClickListener(this);
        }
    
        private void initData(){
            if(sharedPreferences==null){
                sharedPreferences=getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
            }
            etName.setText(sharedPreferences.getString("et1",name));
            etTemper.setText(sharedPreferences.getString("et2","36.2"));
    
            etPosition.setText(sharedPreferences.getString("et3",""));
            Log.i("MainActivity","已自动填写");
        }
        private String getDate(){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");// HH:mm:ss
            //获取当前时间
            Date date1 = new Date(System.currentTimeMillis());
    
            return  simpleDateFormat.format(date1);
        }
    
        private void initUI(){
            etName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                }
                @Override
                public void afterTextChanged(Editable s) {
                    if(sharedPreferences==null){
                        sharedPreferences=getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
                    }
                    SharedPreferences.Editor edit=sharedPreferences.edit();
                    edit. putString("Name",etName.getText().toString());
                    edit.commit();
                }
            });
            etTemper.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                }
                @Override
                public void afterTextChanged(Editable s) {
                    if(sharedPreferences==null){
                        sharedPreferences=getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
                    }
                    SharedPreferences.Editor edit=sharedPreferences.edit();
                    edit. putString("Temper",etTemper.getText().toString());
                    edit.commit();
                }
            });
            etPosition.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                }
                @Override
                public void afterTextChanged(Editable s) {
                    if(sharedPreferences==null){
                        sharedPreferences=getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
                    }
                    SharedPreferences.Editor edit=sharedPreferences.edit();
                    edit. putString("Position",etPosition.getText().toString());
                    edit.commit();
                }
            });
    
            a.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pp+="无";
                }
            });
    
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pp+="2020年12月27日至今去过或现在居住在中高风险地区;";
                    t1.setVisibility(View.VISIBLE);
    
                }
            });
    
            c.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pp+="本人或家人正在集中隔离;";
                    t2.setVisibility(View.VISIBLE);
    
                }
            });
    
    
            d.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pp += "今日居住地异动;";
                    t3.setVisibility(View.VISIBLE);
    
                }
            });
    
    
            e.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    pp+="其他情况;";
                    t4.setVisibility(View.VISIBLE);
    
                }
            });
    
    
            putDatabase.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    SQLiteDatabase db=dbHelper.getWritableDatabase();
                    ContentValues values=new  ContentValues();
                    String name=etName.getText().toString();//获取名字信息
                    String temper=etTemper.getText().toString();//获取体温信息
                    String date=etDate.getText().toString();//获取日期信息
                    String position=etPosition.getText().toString();//获取位置信息
                    pp=pp+t1.getText().toString()+"   ";
                    pp=pp+t2.getText().toString()+"   ";
                    pp=pp+t3.getText().toString()+"   ";
                    pp=pp+t4.getText().toString()+"   ";
                    values.put("姓名",name);
                    values.put("体温",temper);
                    values.put("日期时间",date);
                    values.put("所在地",position);
                    values.put("状况",pp);
                    pp="";
                    if(name.equals("")||temper.equals("")||date.equals("")||position.equals(""))
                    {
                        Toast.makeText(com.example.myapplication2.MainActivity.this, "信息不全,请补充", Toast.LENGTH_SHORT).show();
                    }
                    else{
                        System.out.println(date);
                        db.insert("TTList3",null,values);
                        values.clear(); //注意别漏掉
                        Toast.makeText(com.example.myapplication2.MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
    
                        etName.setText("");//保存成功清空学号和姓名信息
                        etTemper.setText("");
                        etDate=findViewById(R.id.date);
                    }
                }
            });
            startLocation.setOnClickListener(new View.OnClickListener(){
                public void onClick(View v){
    
                }
            });
    
        }
    
    
        private void getPersimmions() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ArrayList<String> permissions = new ArrayList<String>();
    
                // * 定位权限为必须权限,用户如果禁止,则每次进入都会申请
                // 定位精确位置
    
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }
    
                //  读写权限和电话状态权限非必要权限(建议授予)只会申请一次,用户同意或者禁止,只会弹一次
                // 读写权限
    
                if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    String permissionInfo = "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny 
    ";
                }
                if (permissions.size() > 0) {
                    requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
                }
            }
        }//定位
    
        @TargetApi(23)
        private boolean addPermission(ArrayList<String> permissionsList, String permission) {
            // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(permission)) {
                    return true;
                } else {
                    permissionsList.add(permission);
                    return false;
                }
            } else {
                return true;
            }
        }//定位
    
        @TargetApi(23)
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            // TODO Auto-generated method stub
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == REQUEST_PERMISSION_CODE) {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功");
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {
                    Log.i("onPermissionsResult:", "用户拒绝了权限申请");
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("permission")
                            .setMessage("点击允许才可以使用我们的app哦")
                            .setPositiveButton("去允许", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {
                                    if (alertDialog != null && alertDialog.isShowing()) {
                                        alertDialog.dismiss();
                                    }
                                    ActivityCompat.requestPermissions(MainActivity.this,
                                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                }
                            });
                    alertDialog = builder.create();
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            }
    
        }//定位
    
    
        @Override
        protected void onStart() {
            super.onStart();
            // -----------location config ------------
            locationService = ((LocationApplication) getApplication()).locationService;
            //获取locationservice实例,建议应用中只初始化1个location实例,然后使用,可以参考其他示例的activity,都是通过此种方式获取locationservice实例的
            locationService.registerListener(mListener);
            //注册监听
            int type = getIntent().getIntExtra("from", 0);
            if (type == 0) {
                LocationService.setLocationOption(locationService.getDefaultLocationClientOption());
            } else if (type == 1) {
                locationService.start();
            }
            startLocation.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    if (startLocation.getText().toString().equals("定位")) {
                        locationService.start();// 定位SDK
                        // start之后会默认发起一次定位请求,开发者无须判断isstart并主动调用request
                        startLocation.setText("停止定位");
                    } else {
                        locationService.stop();
                        startLocation.setText("定位");
                    }
                }
            });
        }//定位
        @Override
        protected void onStop() {
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop(); //停止定位服务
            super.onStop();
        }//定位
        private final BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {//定位
                if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                    if(location.getAddrStr() !=null) {
                        System.out.println(location.getAddrStr());
                        etPosition.setText(location.getAddrStr() );
                        locationService.stop();
                        startLocation.setText("定位");
                    }
                    if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                        System.out.println("网络定位成功");
                    } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                        System.out.println("离线定位成功,离线定位结果也是有效的");
                    } else if (location.getLocType() == BDLocation.TypeServerError) {
                        System.out.println("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
                    } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                        System.out.println("网络不同导致定位失败,请检查网络是否通畅");
                    } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                        System.out.println("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
                    }
                }
            }
        };
    
    
        private void exportExcel(Context context) {
            String path = Environment.getExternalStorageDirectory().getPath() + "/test3";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            File files = new File(file.getPath()+"/"+"text3.xls");
            if (!files.exists()) {// 文件存在返回false
                try {
                    files.createNewFile();//创建文件
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Toast.makeText(MainActivity.this, "存储到"+files.getPath(), Toast.LENGTH_SHORT).show();
            initExcel(files);
        }//创建表格
    
    
    
        public  void initExcel(File filePath){
    
            try {
                WritableWorkbook workbook = null;
                if (!filePath.exists()) {
                    filePath.createNewFile();
                }
    
    
    
    
                workbook = Workbook.createWorkbook(filePath);
                WritableSheet sheet = workbook.createSheet("test3",0);
                sheet.mergeCells(0,0,6,0);
                Label header = new Label(0,0,"学生14天健康情况登记表");
                sheet.addCell(header);
                sheet.mergeCells(0,1,3,1);
                sheet.addCell(new Label(0,1,"单位名称:"+cla));
    
                sheet.mergeCells(4,1,6,1);
                sheet.addCell(new Label(4,1,"填表日期:"+getDate()));
    
                sheet.addCell(new Label(0,2,"姓名"));
                sheet.addCell(new Label(1,2,name));
                sheet.mergeCells(1,2,3,2);
                sheet.addCell(new Label(4,2,"学号:"));
                sheet.addCell(new Label(5,2,xuehao));
                sheet.mergeCells(5,2,6,2);
                sheet.addCell(new Label(0,3,"目前健康状况:"));
                sheet.mergeCells(1,3,3,3);
                sheet.addCell(new Label(1,3,"正常"));
                sheet.addCell(new Label(4,3,"手机号"));
                sheet.addCell(new Label(5,3,phone));
                sheet.mergeCells(5,3,6,3);
                sheet.mergeCells(0,4,6,4);
                sheet.addCell(new Label(0,4,"每日体温、健康状况监测(周期14天)"));
                String [] colName = {"日期","每日体温℃","健康状况","当日所在地","备注"};
                sheet.mergeCells(3,5,4,5);
                sheet.mergeCells(5,5,6,5);
                for (int col=0;col<3;col++){
                    sheet.addCell(new Label(col, 5, colName[col]));
                }
                sheet.addCell(new Label(3, 5, colName[3]));
                sheet.addCell(new Label(5, 5, colName[4]));
    
                int j=6;
                dbHelper=new DatabaseHelper(this,"TTList3.db",null,3);
                SQLiteDatabase db2=dbHelper.getWritableDatabase();
                Cursor cursor2 = db2.query("TTList3", null, "姓名=?", new String[]{name}, null, null, null);//读取数据库所有信息
                // Cursor cursor=db.query("tt",null,"专业=?",new String[]{"软件工程"},
                //null,null,null);//读取数据库里面专业是软件工程的所有信息
                if(cursor2.moveToFirst()){
                    do{
                        String name=cursor2.getString(cursor2.getColumnIndex("姓名"));
                        String tt=cursor2.getString(cursor2.getColumnIndex("体温"));
                        String time=cursor2.getString(cursor2.getColumnIndex("日期时间"));
                        String location=cursor2.getString(cursor2.getColumnIndex("所在地"));
    
                        String str = time.substring(0, time.indexOf(" "));
                        sheet.addCell(new Label(0,j,str));
                        sheet.addCell(new Label(1,j,tt));
                        double k = Double.parseDouble(tt);
                        if (k < 37.3 &&k > 35) {
                            sheet.addCell(new Label(2,j,"正常"));
                        } else {
                            sheet.addCell(new Label(2,j,"异常"));
                        }
                        sheet.addCell(new Label(3,j,location));
                        j++;
                    }while (cursor2.moveToNext());
                }
                cursor2.close();
    
    
    
                sheet.mergeCells(0,20,6,20);
                sheet.addCell(new Label(0,20,"本人承诺:自觉履行疫情防控责任和义务,保证以上填报信息全部属实,如有隐瞒,自愿承担相应法律后果。"));
                sheet.mergeCells(0,21,1,21);
                sheet.addCell(new Label(0,21,"本人签字:"));
                sheet.mergeCells(2,21,3,21);
                sheet.addCell(new Label(4,21,"签字日期:"));
                sheet.mergeCells(5,21,6,21);
                workbook.write();
                workbook.close();
    
            } catch (IOException e) {
                e.printStackTrace();
            } catch (RowsExceededException e) {
                e.printStackTrace();
            } catch (WriteException e) {
                e.printStackTrace();
            }
    
        }//对表格处理
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.but2://执行按钮4
                    Intent intent =new Intent();
                    intent.putExtra("name",name);
                    intent.setClass(getApplicationContext(), liulan.class);
                    this.startActivity(intent);
                    break;
    
                case R.id.button3:
                    Intent intent2 =new Intent();
                    intent2.setClass(getApplicationContext(), Firstactivity.class);
                    this.startActivity(intent2);
                    break;
    
                case R.id.button4:
                    Intent intent6 =new Intent();
                    intent6.putExtra("name",name);
                    intent6.setClass(getApplicationContext(), shanchu.class);
                    this.startActivity(intent6);
                    break;
    
                case R.id.button7:
                    exportExcel(this);
                   break;
                case R.id.open_button:
                    openDir();
                    break;
    
    
            }
        }
    
        private void openDir() {
    
            File file = new File(filePath);
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("/test3");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setDataAndType(Uri.fromFile(file), "files/test3/text3.xls");
            try {
                startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show();
            }
        }
    
        private void requestPermission() {
            if (Build.VERSION.SDK_INT > 23) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        permissions[0])
                        == PackageManager.PERMISSION_GRANTED) {
                    //授予权限
                    Log.i("requestPermission:", "用户之前已经授予了权限!");
                } else {
                    //未获得权限
                    Log.i("requestPermission:", "未获得权限,现在申请!");
                    requestPermissions(permissions
                            , REQUEST_PERMISSION_CODE);
                }
            }
    
        }
    
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    
    
        private void showDialogTipUserRequestPermission() {
            ActivityCompat.requestPermissions(this, permissions, 321);
        }
    
    
    
    }
  • 相关阅读:
    分布式事务slides
    为什么jdk中把String类设计成final
    Struts 体系结构与工作原理 图
    在指定路径或者是文件名查找指定的字符串
    Apache Avro 与 Thrift 比较
    SSL请求trustStore的两种注册方式
    java中的split使用的是正则表达式
    所有ghost操作系统大全
    Tomcat帮助文档翻译 未完成
    ORACLE基本配置
  • 原文地址:https://www.cnblogs.com/Nojava/p/14907522.html
Copyright © 2011-2022 走看看