Day1101

mac2025-12-17  8

登录注册,下载上传

登录注册登录注册javabean类以及其他功能类 (JavaBean类太长了就不写了)OkHttpUtils MyListener下载上传 在第二个show Activity页面小功能 Adapter异步AsyncTask存储MP4文件名

登录注册

登录

package com.example.work; import android.Manifest; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.work.HttpUtils.HttpUtils; import com.example.work.JavaBean.JsonBean; import com.example.work.JavaBean.LoginBean; import com.example.work.Listener.MyListener; import com.google.gson.Gson; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private EditText editUser; private EditText editPwd; private Button butLogin; private Button butRegister; private HttpUtils instance; private String path_f = "https://www.apiopen.top/createUserKey"; private String path_log = "https://www.apiopen.top/login"; private String appKey = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] str = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(str, 100); } instance = HttpUtils.getInstance(); firstRun(); initView(); initData(); } private void firstRun() { Map<String,String> map = new HashMap<>(); map.put("appId","com.pym"); map.put("passwd","1121"); instance.doPost(path_f, map, new MyListener() { @Override public void getMsg(String json) { JsonBean jsonBean = new Gson().fromJson(json, JsonBean.class); appKey = jsonBean.getData().getAppkey(); Log.i(TAG, "getMsg: "+jsonBean.toString()); } @Override public void getError(String error) { } }); } private void initData() { toRegister(); } private void toRegister() { butRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RegisterActivity.class); intent.putExtra("appKey",appKey); startActivity(intent); } }); butLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //https://www.apiopen.top/login?key=00d91e8e0cca2b76f515926a36db68f5&phone=13594347817&passwd=123456 String user = editUser.getText().toString().trim(); String pwd = editPwd.getText().toString().trim(); final Map<String,String> map = new HashMap<>(); map.put("key",appKey); map.put("phone",user); map.put("passwd",pwd); instance.doPost(path_log, map, new MyListener() { @Override public void getMsg(String json) { LoginBean loginBean = new Gson().fromJson(json, LoginBean.class); String msg = loginBean.getMsg(); Log.i(TAG, "getMsg: "+msg); if(msg.equals("成功!")){ Toast.makeText(MainActivity.this, "登陆成功!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, ShowActivity.class); startActivity(intent); finish(); }else{ Toast.makeText(MainActivity.this, "用户名或者密码错误!", Toast.LENGTH_SHORT).show(); } } @Override public void getError(String error) { } }); } }); } private void initView() { editUser = (EditText) findViewById(R.id.edit_user); editPwd = (EditText) findViewById(R.id.edit_pwd); butLogin = (Button) findViewById(R.id.but_login); butRegister = (Button) findViewById(R.id.but_register); } }

注册

package com.example.work; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.work.HttpUtils.HttpUtils; import com.example.work.JavaBean.RegisterBean; import com.example.work.Listener.MyListener; import com.google.gson.Gson; import java.util.HashMap; import java.util.Map; public class RegisterActivity extends AppCompatActivity { private static final String TAG = "RegisterActivity"; private EditText editReUser; private EditText editRePwd; private Button butReRegister; private String register_path = "https://www.apiopen.top/createUser"; private String appKey = ""; private HttpUtils instance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); initView(); instance = HttpUtils.getInstance(); Intent intent = getIntent(); appKey = intent.getStringExtra("appKey"); } private void initView() { editReUser = (EditText) findViewById(R.id.edit_re_user); editRePwd = (EditText) findViewById(R.id.edit_re_pwd); butReRegister = (Button) findViewById(R.id.but_re_register); buttonListener(); } private void buttonListener() { butReRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String user = editReUser.getText().toString().trim(); String pwd = editRePwd.getText().toString().trim(); /** * https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&phone=13594347817&passwd=123654 */ Map<String,String> map = new HashMap<>(); map.put("key",appKey); map.put("phone",user); map.put("passwd",pwd); instance.doPost(register_path, map, new MyListener() { @Override public void getMsg(String json) { RegisterBean registerBean = new Gson().fromJson(json, RegisterBean.class); String msg = registerBean.getMsg(); Log.i(TAG, "getMsg: "+msg); if(msg.equals("成功!")){ Toast.makeText(RegisterActivity.this, "注册成功!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterActivity.this, MainActivity.class); startActivity(intent); finish(); }else{ Toast.makeText(RegisterActivity.this, "用户已被注册!", Toast.LENGTH_SHORT).show(); } } @Override public void getError(String error) { } }); } }); } }

javabean类以及其他功能类 (JavaBean类太长了就不写了)

OkHttpUtils
package com.example.work.HttpUtils; import android.os.Environment; import android.os.Handler; import android.util.Log; import com.example.work.Listener.MyListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class HttpUtils { private static HttpUtils registerUtils = null; private static OkHttpClient client = null; private Handler handler = new Handler(); private HttpUtils(){ client = new OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20,TimeUnit.SECONDS) .build(); } public static HttpUtils getInstance(){ if (registerUtils == null) { synchronized (Object.class){ if (registerUtils == null) { registerUtils = new HttpUtils(); } } } return registerUtils; } public void doPost(String path, Map<String,String> map, final MyListener listener){ FormBody.Builder builder = new FormBody.Builder(); Set<Map.Entry<String, String>> entries = map.entrySet(); for (Map.Entry<String, String> entry : entries) { builder.add(entry.getKey(),entry.getValue()); } Request request = new Request.Builder() .post(builder.build()) .url(path) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { listener.getError(e.getMessage()); } }); } @Override public void onResponse(Call call, Response response) throws IOException { ResponseBody body = response.body(); final String string = body.string(); handler.post(new Runnable() { @Override public void run() { listener.getMsg(string); } }); } }); } public void downLoad(String url, final File path, final MyListener listener){ Request request = new Request.Builder() .url(url) .get() .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { listener.getError(e.getMessage()); } }); } @Override public void onResponse(Call call, Response response) throws IOException { ResponseBody body = response.body(); InputStream is = body.byteStream(); boolean flag = false; int len = 0; byte[] b = new byte[1024]; FileOutputStream fos = new FileOutputStream(path); while((len = is.read(b)) != -1){ fos.write(b, 0, len); flag = true; } handler.post(new Runnable() { @Override public void run() { listener.getMsg("下载成功!"); } }); Log.i("---", "onResponse: "+flag); fos.close(); is.close(); } }); } public void upLoad(String url, String name, File path, final MyListener listener){ RequestBody requestBody = RequestBody.create(MediaType.parse("media.mp4"), path); MultipartBody file = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", name,requestBody) .build(); Request request = new Request.Builder() .url(url) .post(file) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { listener.getError(e.getMessage()); } }); } @Override public void onResponse(Call call, Response response) throws IOException { handler.post(new Runnable() { @Override public void run() { listener.getMsg("下载成功!"); } }); } }); } }

MyListener

package com.example.work.Listener; public interface MyListener { void getMsg(String json); void getError(String error); }

下载上传 在第二个show Activity页面

package com.example.work; import android.Manifest; import android.content.DialogInterface; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import android.widget.VideoView; import com.example.work.Entity.MyAdapter; import com.example.work.Entity.MyAsyncTask; import com.example.work.Entity.Share; import com.example.work.HttpUtils.HttpUtils; import com.example.work.JavaBean.VideoBean; import com.example.work.Listener.MyListener; import java.io.File; import java.util.ArrayList; import java.util.List; public class ShowActivity extends AppCompatActivity { private String path = "https://www.apiopen.top/satinApi?type=1&page=2"; private String upLoad_path = "http://10.1.3.227/hfs/"; private ListView listView; private List<VideoBean.DataBean> totalList = new ArrayList<>(); private MyAdapter adapter; private HttpUtils instance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},100); instance = HttpUtils.getInstance(); initView(); } private void initView() { listView = (ListView) findViewById(R.id.list_view); adapter = new MyAdapter(totalList,this); listView.setAdapter(adapter); new MyAsyncTask(totalList,adapter).execute(path); listViews(); } private void listViews() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(totalList.get(position).getVideouri().equals("") ||totalList.get(position).getVideouri() == null){ Toast.makeText(ShowActivity.this, "抱歉,当前视频不存在或已被删除", Toast.LENGTH_SHORT).show(); return; } Hit(position); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if(totalList.get(position).getVideouri().equals("") ||totalList.get(position).getVideouri() == null){ Toast.makeText(ShowActivity.this, "抱歉,当前视频不存在或已被删除", Toast.LENGTH_SHORT).show(); return false; } hitLong(position); return true; } }); } //长点击 private void hitLong(final int position) { AlertDialog.Builder builder = new AlertDialog.Builder(ShowActivity.this); builder.setTitle("提示信息:"); builder.setMessage("您确定要上传此视频吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File directory = Environment.getExternalStorageDirectory(); File file = new File(directory, Share.list.get(position)); if(!file.exists()){ Toast.makeText(ShowActivity.this, "此文件不存在,无法上传!", Toast.LENGTH_SHORT).show(); return; } instance.upLoad(upLoad_path, Share.list.get(position), file, new MyListener() { @Override public void getMsg(String json) { Toast.makeText(ShowActivity.this, ""+json, Toast.LENGTH_SHORT).show(); } @Override public void getError(String error) { Toast.makeText(ShowActivity.this, ""+error, Toast.LENGTH_SHORT).show(); } }); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } private void Hit(final int position) { AlertDialog.Builder builder = new AlertDialog.Builder(ShowActivity.this); builder.setTitle("提示信息:"); builder.setMessage("您确定要下载此视频吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File directory = Environment.getExternalStorageDirectory(); File file = new File(directory, Share.list.get(position)); instance.downLoad(totalList.get(position).getVideouri(), file, new MyListener() { @Override public void getMsg(String json) { Toast.makeText(ShowActivity.this, ""+json, Toast.LENGTH_SHORT).show(); } @Override public void getError(String error) { Toast.makeText(ShowActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); } }); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }

小功能 Adapter

package com.example.work.Entity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.work.JavaBean.VideoBean; import com.example.work.R; import java.util.List; public class MyAdapter extends BaseAdapter { private List<VideoBean.DataBean> totalList; private Context context; private LayoutInflater layoutInflater; public MyAdapter(List<VideoBean.DataBean> totalList, Context context) { this.totalList = totalList; this.context = context; layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return totalList.size(); } @Override public Object getItem(int position) { return totalList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.layout_video_list,null); holder.imageView_pic = convertView.findViewById(R.id.image_pic); holder.textView_str = convertView.findViewById(R.id.text_str); holder.textView_title = convertView.findViewById(R.id.text_title); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } holder.textView_title.setText(totalList.get(position).getName()); holder.textView_str.setText(totalList.get(position).getText()); Glide.with(context).load(totalList.get(position).getProfile_image()).into(holder.imageView_pic); return convertView; } class ViewHolder{ ImageView imageView_pic; TextView textView_title; TextView textView_str; } }

异步AsyncTask

package com.example.work.Entity; import android.os.AsyncTask; import com.example.work.JavaBean.VideoBean; import com.google.gson.Gson; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public class MyAsyncTask extends AsyncTask<String, Void , List<VideoBean.DataBean>> { private List<VideoBean.DataBean> totalList; private MyAdapter adapter; public MyAsyncTask(List<VideoBean.DataBean> totalList, MyAdapter adapter) { this.totalList = totalList; this.adapter = adapter; } @Override protected List<VideoBean.DataBean> doInBackground(String... strings) { try { URL url = new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if(connection.getResponseCode() == 200){ InputStream is = connection.getInputStream(); int len = 0; byte[] b = new byte[1024]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = is.read(b)) != -1) { bos.write(b, 0, len); } bos.close(); is.close(); VideoBean videoBean = new Gson().fromJson(bos.toString(), VideoBean.class); return videoBean.getData(); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(List<VideoBean.DataBean> dataBeans) { super.onPostExecute(dataBeans); if(dataBeans != null && dataBeans.size() > 0){ totalList.addAll(dataBeans); for (int i = 0; i < totalList.size(); i++) { Share.list.add("a"+i+".mp4"); } adapter.notifyDataSetChanged(); } } }

存储MP4文件名

package com.example.work.Entity; import java.util.ArrayList; import java.util.List; public class Share { public static List<String> list = new ArrayList<>(); }
最新回复(0)