您的位置:首页 > 运维架构 > Tomcat

Android——Tomcat版本更新下载+头像照片上传到Tomcat

2016-09-05 20:22 609 查看
Android——Tomcat版本更新下载+头像照片上传到Tomcat

package com.example.schoolappzyf;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.schoolappzyf.util.File5Uitlity;
import com.example.schoolappzyf.util.HttpUtil;
import com.example.schoolappzyf.util.UrlUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadActivity extends AppCompatActivity {
private TextView tv1, tv2,gx;
private int i,vid;
private Button denglu, tuichu;
private NotificationManager nm;
private NotificationCompat.Builder builder;
private Notification nf;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
denglu = (Button) findViewById(R.id.denglu);
tuichu = (Button) findViewById(R.id.tuichu);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
gx = (TextView) findViewById(R.id.gx);
String ur2 = UrlUtil.schoolUrl + "apk";
new Getapk().execute(ur2);

try {
//获取当前版本
vid = getPackageManager().getPackageInfo(this.getPackageName(), 0)
.versionCode;
Log.d("????1?", vid + "");
tv1.setText(vid + "");

} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}

tuichu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});

denglu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (vid<i) {
String url = UrlUtil.schoolUrl + "apk/cc.apk";
new DownLoasAPK().execute(url);
}else {
Toast.makeText(getBaseContext(), "不需要更新", Toast.LENGTH_SHORT).show();
}
}
});
//构建通知栏
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder =
new NotificationCompat.Builder(getBaseContext());
builder.setContentTitle("下载");
builder.setContentText("校园通正在下载");
builder.setSmallIcon(R.mipmap.ic_launcher);

}

public class DownLoasAPK extends AsyncTask<String, Integer, String> {
int i = 0;

@Override
protected void onPreExecute() {
super.onPreExecute();
nf = builder.build();
nm.notify(0, nf);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}

//子线程
@Override
protected String doInBackground(String... strings) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// File5Uitlity.getInstance(DownloadActivity.this,
// getPackageName());
// File root = Environment.getExternalStorageDirectory();
// File apk = new File(root+"/"+getPackageName(),"testtt.apk");
// Log.d("?????66",root+"");

//
String root = File5Uitlity.getInstance(DownloadActivity.this, getPackageName())
.ROOT_CACHE;

Log.d("?????++", root);
File apk = new File(root, "testtt.apk");
Log.d("?????++", apk + "");

bos = new BufferedOutputStream(
new FileOutputStream(apk));
int next = 0;
int length = connection.getContentLength();
double currentprogress = 0;
byte[] b = new byte[1024 * 1024 * 10];
while ((next = is.read(b)) > 0) {

currentprogress += next;
bos.write(b, 0, next);
Log.d("?????", currentprogress + "");
int progress = (int) (currentprogress / length * 100);
publishProgress(progress);

}

}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {

try {
if (bos != null) {

bos.flush();
bos.close();
}

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

return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
;
if (i == values[0]) {
return;
}
i = values[0];
builder.setProgress(100, values[0], false);
Log.d("====values=", "" + values[0]);
nf = builder.build();
nm.notify(0, nf);
if (values[0] == 100) {
Intent it = new Intent(Intent.ACTION_VIEW);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

it.setDataAndType(Uri.parse("file:///sdcard/"
+ "imagCache" + "/testtt.apk"),
"application/vnd.android.package-archive");
PendingIntent pi = PendingIntent
.getActivity(DownloadActivity.this,
0,
it,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi)
.setAutoCancel(true)
.setContentText("点击安装")
.setContentTitle("下载完成");
nf = builder.build();
nm.notify(0, nf);
}

}

}

public class Getapk extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... strings) {
// url= UrlUtil.schoolUrl+strings[0];

return HttpUtil.HttpGet(strings[0]);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s == null) {
Toast.makeText(getBaseContext(), "没有数据网路不好", Toast.LENGTH_SHORT).show();

} else {
try {
JSONObject obj = new JSONObject(s);
tv2.setText(obj.getString("vid"));
i= Integer.parseInt(obj.getString("vid"));
if (vid<i){
gx.setText("新版本可点击更新");
}
} catch (JSONException e) {
e.printStackTrace();
}

}

}
}

}


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.schoolappzyf.DownloadActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="70dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/gx"
android:text="最新版本不需更新"
android:gravity="center"
android:textSize="25sp"

/>
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:textSize="25sp"
android:text="当前版本"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:textSize="25sp"
android:text="无"
android:id="@+id/tv1"
android:layout_marginLeft="260dp"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:textSize="25sp"
android:text="现在版本"

/>
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:textSize="25sp"
android:text="无"
android:id="@+id/tv2"
android:layout_marginLeft="260dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/denglu"
android:text="更新下载"
android:textSize="25sp"/>
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/tuichu"
android:text="稍后更新并退出"
android:textSize="25sp"/>
</LinearLayout>

</RelativeLayout>


保存文件位置工具
package com.example.schoolappzyf.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class File5Uitlity {
public static String ROOT_CACHE;
public static File5Uitlity instance = null;
private File5Uitlity() {
}
//创建文件夹
public static File5Uitlity getInstance(Context context, String root_dir) {
if (instance == null) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
ROOT_CACHE = (Environment.getExternalStorageDirectory() + "/"
+ root_dir + "/");
} else {
ROOT_CACHE = (context.getFilesDir().getAbsolutePath() + "/"+root_dir+"/");
}
File dir = new File(ROOT_CACHE);
if (!dir.exists()) {
dir.mkdirs();
}
instance = new File5Uitlity();
}else{
File dir = new File(ROOT_CACHE+"/"+root_dir);
if (!dir.exists()) {
dir.mkdirs();
}
}
return instance;
}
public File makeDir(String dir) {
File fileDir = new File(ROOT_CACHE + dir);
if (fileDir.exists()) {
return fileDir;
} else {
fileDir.mkdirs();
return fileDir;
}
}
//判断文件是否存在SD卡
public static boolean fileExists(String fileName){
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)){
return false;
}else{

File file = new File(ROOT_CACHE,fileName);
return file.exists();
}
}
//保存文件到SD卡
public static String saveFileToSdcard(String fileName,String content){
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)){
Log.d("=====","文件保存失败11");

return "SD卡未就绪";
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(ROOT_CACHE+"/"+fileName);
fos.write(content.getBytes());
return "ok";
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
//读取SD卡文件
public static String readFileFromSdcard(String fileName){
String statue = Environment.getExternalStorageState();
if(!statue.equals(Environment.MEDIA_MOUNTED)){
return "";
}else{
BufferedReader reader =null;
FileInputStream fis = null;
StringBuilder sbd = new StringBuilder();
try {
fis = new FileInputStream(ROOT_CACHE+"/"+fileName);
reader = new BufferedReader(new InputStreamReader(fis));
String row = "";
while ((row=reader.readLine())!=null){
sbd.append(row);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sbd.toString();
}
}

}

package com.example.schoolappzyf.util;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

//		String httpUrl="http://apis.baidu.com/showapi_open_bus/channel_news/search_news";
//		String httpArg="channelId=5572a109b3cdc86cf39001db&channelName=%E5%9B%BD%E5%86%85%E6%9C%80%E6%96%B0&title=%E4%B8%8A%E5%B8%82&page=1&needContent=0&needHtml=0";

public class FileUitlity6 {
public static String ROOT_CACHE;
public static FileUitlity6 instance = null;
private FileUitlity6() {
}
//创建文件夹
public static FileUitlity6 getInstance(Context context,String root_dir) {
if (instance == null) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
ROOT_CACHE = (Environment.getExternalStorageDirectory() + "/"
+ root_dir + "/");
} else {

}
File dir = new File(ROOT_CACHE);
if (!dir.exists()) {
dir.mkdirs();
}
instance = new FileUitlity6();}
//		else{
//			ROOT_CACHE = (context.getFilesDir().getAbsolutePath() + "/"+root_dir+"/");
//			File dir=new File(ROOT_CACHE);
//			if (!dir.exists()){
//				dir.mkdirs();
//			}
//		}
return instance;
}
//
public File makeDir(String dir) {
File fileDir = new File(ROOT_CACHE + dir);
if (fileDir.exists()) {
return fileDir;
} else {
fileDir.mkdirs();
return fileDir;
}
}

//判断文件是否存在SD卡
public static boolean fileExists(String fileName){
String state=Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)){
return false;
}else {
File root=Environment.getExternalStorageDirectory();
File file=new File(root,fileName);
return file.exists();
}
}

//保存文件
public static String saveFileToSdcard(String fileName, String content){
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)){
return "SD卡未就绪";
}
File root = Environment.getExternalStorageDirectory();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(root+"/"+fileName);
fos.write(content.getBytes());
return "ok";
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
//读取文件
public static String readFileFromSdcard(String fileName){
String statue=Environment.getExternalStorageState();
if (!statue.equals(Environment.MEDIA_MOUNTED)){
return "";
}else {
File root=Environment.getExternalStorageDirectory();
BufferedReader reader=null;
FileInputStream fis=null;
StringBuilder sbd=new StringBuilder();
try {
fis=new FileInputStream(root+"/"+fileName);
reader=new BufferedReader(new InputStreamReader(fis));
String row="";
while ((row=reader.readLine())!=null){
sbd.append(row);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sbd.toString();
}

}

}
???????????????????????
package com.example.administrator.jreduch07;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.jreduch07.util.FileUitlity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadActivity extends AppCompatActivity {
private Button button ;
private TextView show;
private NotificationManager nm;
private NotificationCompat.Builder builder;
private Notification nf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
button = (Button) findViewById(R.id.download);
show = (TextView) findViewById(R.id.show);
try {//获得当前apk版本号
int vid = getPackageManager().getPackageInfo(getPackageName(),0).versionCode;
show.setText("当前版本号:"+vid);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "http://192.168.1.33:8080/SchoolLife/apk/cc.apk";
new DownLoadApk().execute(url);
}
});
//构建通知栏
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder =
new NotificationCompat.Builder(getBaseContext());
builder.setContentTitle("下载");
builder.setContentText("校园通正在下载");
builder.setSmallIcon(R.mipmap.ic_launcher);
}
public class DownLoadApk extends AsyncTask<String,Integer,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
nf = builder.build();
nm.notify(0,nf);
}
@Override
protected String doInBackground(String... strings) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5*1000);
connection.setReadTimeout(5*1000);
if(connection.getResponseCode()==200){
is = connection.getInputStream();
FileUitlity.getInstance(DownloadActivity.this,
getPackageName());
File root = Environment.getExternalStorageDirectory();
File apk = new File(root+"/"+getPackageName(),"test.apk");
bos = new BufferedOutputStream(
new FileOutputStream(apk));
int next = 0;
byte[] b = new byte[1024*1024*10];
int length = connection.getContentLength();
double currentProgress = 0;
while((next=is.read(b))>0){
currentProgress += next ;
int progress = (int)(currentProgress/length *100);
publishProgress(progress);
bos.write(b,0,next);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bos!=null){
bos.flush();
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
builder.setProgress(100,values[0],false);
nf = builder.build();
nm.notify(0,nf);
if(values[0]==100){
Intent it = new Intent(Intent.ACTION_VIEW);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
it.setDataAndType(Uri.parse("file:///sdcard/"
+getPackageName()+"/test.apk"),
"application/vnd.android.package-archive");
PendingIntent pi  = PendingIntent
.getActivity(DownloadActivity.this,
0,
it,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi)
.setAutoCancel(true)
.setContentText("点击安装")
.setContentTitle("下载完成");
nf = builder.build();
nm.notify(0,nf);
}
}
}
}


头像上传
package com.example.schoolappzyf;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.schoolappzyf.dao.UserdlDao;
import com.example.schoolappzyf.entity.User;
import com.example.schoolappzyf.util.FileUitlity1;
import com.example.schoolappzyf.util.RoundImageView;
import com.example.schoolappzyf.util.StringPostRequest;
import com.example.schoolappzyf.util.UrlUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class SZActivity extends AppCompatActivity implements View.OnClickListener {
private PopupWindow pw;
private View popView;
private TextView name,tv1,show,tv3;
private Button bc,exit;
private Switch sszd,ssjz;
private RoundImageView riv;
private RequestQueue requestQueue;

private UserdlDao userdlDao;
private User user;

private SharedPreferences sp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sz);
requestQueue = Volley.newRequestQueue(this);
getSupportActionBar().hide();
//加载PopWindow中的布局
popView = getLayoutInflater().inflate(R.layout.pop_layout, null);
//从主布局中取得控件

//从PopWindow布局中取得控件
Button xc = (Button)popView.findViewById(R.id.xc);
Button xj = (Button)popView.findViewById(R.id.xj);
Button bt = (Button)popView.findViewById(R.id.bt);
name=(TextView)findViewById(R.id.name);
show=(TextView)findViewById(R.id.show);
tv3=(TextView)findViewById(R.id.tv3);

ssjz=(Switch)findViewById(R.id.ssjz);
sszd=(Switch)findViewById(R.id.sszd);
bc=(Button)findViewById(R.id.bc);
exit=(Button)findViewById(R.id.exit);

tv3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getBaseContext(),DownloadActivity.class);
startActivity(intent);
}
});

bc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor=sp.edit();
editor.putBoolean("jzmm",ssjz.isChecked());
editor.putBoolean("zddl",sszd.isChecked());
editor.commit();
}
});
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
userdlDao.delectAll();
Intent intent=new Intent(getBaseContext(),SchoolAppActivity.class);
startActivity(intent);
}
});

riv = (RoundImageView) findViewById(R.id.riv);
tv1=(TextView)findViewById(R.id.tv1);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getBaseContext(),XGMMActivity.class);
startActivity(intent);
}
});

userdlDao=new UserdlDao(getBaseContext());
user=userdlDao.searchMewsTop().get(0);
name.setText(userdlDao.searchMewsTop().get(0).getStuName());
show.setText("学号:"+user.getUno()+"\n"+"用户名:"+userdlDao.searchMewsTop().get(0).getStuName()+"\n"+
"班级:"+userdlDao.searchMewsTop().get(0).getClassName()+"\n"+"系别:"+user.getMajorName()+"\n"+"职位:"+user.getRole()+"\n"
);
Glide.with(SZActivity.this).load(userdlDao.searchMewsTop().get(0).getImg())
.error(R.mipmap.ic_launcher).into(riv);

//注册 本类监听
riv.setOnClickListener(this);
xc.setOnClickListener(this);
xj.setOnClickListener(this);
bt.setOnClickListener(this);
//显示Intent,明确指定要跳转的组件
// Intent intent=new Intent(IntentActivity.this,SecondActivity.class);
// startActivity(intent);

//---------------------------------------

}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {

case R.id.riv://点击头像打开PopWindow
pw=getPopWindow(popView);
break;
case R.id.xc:
phonePhoto();
break;
case R.id.xj:
takephoto();
break;
case R.id.bt:
pw.dismiss();
break;
}
}

/*
* 调用图库
* */
public void phonePhoto(){
Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);

}

/*
* 调用相机
* */
private String capturePath="";
public void takephoto(){
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File parent= FileUitlity1.getInstance(getApplicationContext())
.makeDir("head_imag");
capturePath=parent.getPath()+File.separatorChar+System.currentTimeMillis()+".jpg";
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePath)));
camera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(camera, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode!= Activity.RESULT_OK){

return;
}
//相机返回结果,调用系统裁剪啊
if (requestCode==1){
startPicZoom(Uri.fromFile(new File(capturePath)));

}
//相册返回结果调用系统裁剪
else if (requestCode==2){
Cursor cursor=getContentResolver()
.query(data.getData(),new String[]{MediaStore.Images.Media.DATA}
,null,null,null);
cursor.moveToFirst();
String capturePath=cursor.getString(
cursor.getColumnIndex(
MediaStore.Images.Media.DATA));
cursor.close();
startPicZoom(Uri.fromFile(new File(capturePath)));
}
else if (requestCode==3){
Bundle bundle= data.getExtras();
if (bundle!=null){
final Bitmap bitmap=bundle.getParcelable("data");
riv.setImageBitmap(bitmap);
pw.dismiss();
AlertDialog.Builder alter =
new AlertDialog.Builder(this)
.setPositiveButton("上传", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
uploadImg(bitmap);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});
AlertDialog dialog = alter.create();
dialog.show();
}
}
}
public void uploadImg(Bitmap bitmap){
String url = UrlUtil.LOGIN_URL;
StringPostRequest request = new StringPostRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
user.setImg(s);
userdlDao.update(user);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {

}
});
request.putParams("userName",user.getUno());
request.putParams("pwd",user.getPwd());
request.putParams("headImage","1");
request.putParams("uhead", convertBitmap(bitmap));
requestQueue.add(request);
}

/**
* 将Bitmap转换为Base64编码的字符串
* @param b
* @return
*/
public String convertBitmap(Bitmap b){
ByteArrayOutputStream out = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = out.toByteArray();
byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
return new String(encode);
}

/*
调用系统裁剪功能

*/
public void startPicZoom(Uri uri){
Intent intent=new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri,"image/*");
intent.putExtra("crop","true");//允许裁剪
intent.putExtra("aspectX",1);//设置裁剪比例
intent.putExtra("aspectY",1);
//设置图片宽度高度
intent.putExtra("outputX",150);
intent.putExtra("outputY",150);
intent.putExtra("return-data",true);
startActivityForResult(intent,3);

}

//设置屏幕背景透明度方法
public void backgroundAlpha(float bgAlpha){
WindowManager.LayoutParams ll=getWindow().getAttributes();
ll.alpha=bgAlpha;
getWindow().setAttributes(ll);
}
//构建一个PopWindow
public PopupWindow getPopWindow(View view){
PopupWindow popupWindow=new PopupWindow(view,
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,true);
// popupWindow.setFocusable(true);
//点击pop外面是否消失
popupWindow.setOutsideTouchable(true);

popupWindow.setAnimationStyle(R.style.popStyle);
//设置背景透明度
backgroundAlpha(0.3f);
//————————
//设置View隐藏
riv.setVisibility(View.GONE);
popupWindow.setBackgroundDrawable(new ColorDrawable());
popupWindow.showAtLocation(riv, Gravity.BOTTOM, 0, 0);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//设置背景透明度
backgroundAlpha(1f);
//设置View可见
riv.setVisibility(View.VISIBLE);
}
});
return popupWindow;
}
@Override
protected void onStart() {
super.onStart();
sp=getSharedPreferences("userInfo",MODE_PRIVATE);

Boolean jzmm=sp.getBoolean("jzmm",false);
Boolean zddl=sp.getBoolean("zddl",false);
ssjz.setChecked(jzmm);
sszd.setChecked(zddl);
}
}

头像
package com.example.zyfnewsctzf;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.example.zyfnewsctzf.util.FileUitlity1;
import com.example.zyfnewsctzf.util.RoundImageView;

import java.io.File;

public class MyIntentActivity extends AppCompatActivity implements View.OnClickListener {
private PopupWindow pw;
private View popView;
private RoundImageView riv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent);
getSupportActionBar().hide();
//加载PopWindow中的布局
popView = getLayoutInflater().inflate(R.layout.pop_layout, null);
//从主布局中取得控件

//从PopWindow布局中取得控件
Button xc = (Button)popView.findViewById(R.id.xc);
Button xj = (Button)popView.findViewById(R.id.xj);
Button bt = (Button)popView.findViewById(R.id.bt);

riv = (RoundImageView) findViewById(R.id.riv);
//注册 本类监听

riv.setOnClickListener(this);
xc.setOnClickListener(this);
xj.setOnClickListener(this);
bt.setOnClickListener(this);
//显示Intent,明确指定要跳转的组件
// Intent intent=new Intent(IntentActivity.this,SecondActivity.class);
// startActivity(intent);

//---------------------------------------

}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {

case R.id.riv://点击头像打开PopWindow
pw=getPopWindow(popView);
break;
case R.id.xc:
phonePhoto();
break;
case R.id.xj:
takephoto();
break;
case R.id.bt:
pw.dismiss();
break;
}
}

/*
* 调用图库
* */
public void phonePhoto(){
Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);

}

/*
* 调用相机
* */
private String capturePath="";
public void takephoto(){
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File parent= FileUitlity1.getInstance(getApplicationContext())
.makeDir("head_imag");
capturePath=parent.getPath()+File.separatorChar+System.currentTimeMillis()+".jpg";
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePath)));
camera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(camera, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode!= Activity.RESULT_OK){

return;
}
//相机返回结果,调用系统裁剪啊
if (requestCode==1){
startPicZoom(Uri.fromFile(new File(capturePath)));

}
//相册返回结果调用系统裁剪
else if (requestCode==2){
Cursor cursor=getContentResolver()
.query(data.getData(),new String[]{MediaStore.Images.Media.DATA}
,null,null,null);
cursor.moveToFirst();
String capturePath=cursor.getString(
cursor.getColumnIndex(
MediaStore.Images.Media.DATA));
cursor.close();
startPicZoom(Uri.fromFile(new File(capturePath)));
}
else if (requestCode==3){
Bundle bundle= data.getExtras();
if (bundle!=null){
Bitmap bitmap=bundle.getParcelable("data");
riv.setImageBitmap(bitmap);

}
}
}

/*
调用系统裁剪功能

*/
public void startPicZoom(Uri uri){
Intent intent=new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri,"image/*");
intent.putExtra("crop","true");//允许裁剪
intent.putExtra("aspectX",1);//设置裁剪比例
intent.putExtra("aspectY",1);
//设置图片宽度高度
intent.putExtra("outputX",150);
intent.putExtra("outputY",150);
intent.putExtra("return-data",true);
startActivityForResult(intent,3);

}

//设置屏幕背景透明度方法
public void backgroundAlpha(float bgAlpha){
WindowManager.LayoutParams ll=getWindow().getAttributes();
ll.alpha=bgAlpha;
getWindow().setAttributes(ll);
}
//构建一个PopWindow
public PopupWindow getPopWindow(View view){
PopupWindow popupWindow=new PopupWindow(view,
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,true);
// popupWindow.setFocusable(true);
//点击pop外面是否消失
popupWindow.setOutsideTouchable(true);

popupWindow.setAnimationStyle(R.style.popStyle);
//设置背景透明度
backgroundAlpha(0.3f);
//————————
//设置View隐藏
riv.setVisibility(View.GONE);
popupWindow.setBackgroundDrawable(new ColorDrawable());
popupWindow.showAtLocation(riv, Gravity.BOTTOM, 0, 0);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//设置背景透明度
backgroundAlpha(1f);
//设置View可见
riv.setVisibility(View.VISIBLE);
}
});
return popupWindow;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息