Files
assistant-android/app/src/main/java/com/gh/gamecenter/SuggestionActivity.java
2017-08-29 11:52:04 +08:00

657 lines
26 KiB
Java

package com.gh.gamecenter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import com.gh.base.AppController;
import com.gh.base.BaseActivity;
import com.gh.base.OnRequestCallBackListener;
import com.gh.common.constant.Config;
import com.gh.common.util.BitmapUtils;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.LoginUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PatternUtils;
import com.gh.common.util.SoftInputHidWidgetUtils;
import com.gh.gamecenter.entity.InstallGameEntity;
import com.gh.gamecenter.entity.SuggestionTypeEntity;
import com.gh.gamecenter.entity.UserInfoEntity;
import com.gh.gamecenter.fragment.WaitingDialogFragment;
import com.gh.gamecenter.retrofit.JSONObjectResponse;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.suggest.SuggestPicAdapter;
import com.gh.gamecenter.suggest.SuggestSelectGameAdapter;
import com.gh.gamecenter.suggest.SuggestTypeAdapter;
import com.google.gson.Gson;
import com.lightgame.download.FileUtils;
import com.lightgame.utils.Util_System_Keyboard;
import com.lightgame.utils.Util_System_Phone_State;
import com.lightgame.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.HttpException;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by khy on 2017/3/31.
*/
public class SuggestionActivity extends BaseActivity implements SuggestTypeAdapter.OnSelectTypeListener,
OnRequestCallBackListener<InstallGameEntity> {
@BindView(R.id.suggest_content_et)
EditText mSuggestContentEt;
@BindView(R.id.suggest_pic_rv)
RecyclerView mSuggestPicRv;
@BindView(R.id.suggest_news_link_et)
EditText mSuggestNewsLinkEt;
@BindView(R.id.suggest_news_link_ll)
View mSuggestNewsLinkLl;
@BindView(R.id.suggest_email_et)
EditText mSuggestEmailEt;
@BindView(R.id.suggest_post_btn)
TextView mSuggestPostBtn;
@BindView(R.id.suggest_post_ll)
View suggestPostLl;
@BindView(R.id.suggest_type_rv)
RecyclerView mTypeRv;
@BindView(R.id.suggest_select_game)
TextView mSuggestSelectGame;
@BindView(R.id.suggest_game_text)
TextView mSuggestGameText;
@BindView(R.id.suggest_game_ll)
View mSuggestGameLl;
@BindView(R.id.suggest_scrollview)
ScrollView mScrollView;
private SuggestPicAdapter mAdapter;
private Dialog selectGameDialog;
private WaitingDialogFragment postDialog;
private String[] arrType = {"普通反馈", "功能建议", "发生闪退", "游戏问题", "游戏收录", "文章投稿"};
private int curType = -1;
private SharedPreferences sp;
public static void startSuggestionActivity(Context context, int suggestType, String suggestHintType, String content) {
Intent intent = new Intent(context, SuggestionActivity.class);
intent.putExtra("suggestType", suggestType);
intent.putExtra("suggestHintType", suggestHintType);
intent.putExtra("content", content);
context.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_suggest;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && requestCode == 0x233) {
Uri selectedImage = data.getData();
if (selectedImage == null) {
return;
}
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor == null) {
return;
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Utils.log("picturePath = " + picturePath);
File file = new File(picturePath);
if (file.length() > 8 * 1024 * 1024) {
toast("图片大小不能超过8M");
} else {
mAdapter.addFileList(picturePath);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTitle(getString(R.string.title_suggestion));
curType = getIntent().getExtras().getInt("suggestType");
String suggestContent = getIntent().getExtras().getString("content");
String suggestHintType = getIntent().getExtras().getString("suggestHintType");
if (getIntent().getBundleExtra("data") != null) {
Bundle data = getIntent().getBundleExtra("data");
suggestContent = data.getString("content");
suggestHintType = data.getString("suggestHintType");
curType = data.getInt("suggestType");
}
sp = PreferenceManager.getDefaultSharedPreferences(this);
// 意见反馈类型
mTypeRv.setLayoutManager(new GridLayoutManager(this, 2) {
@Override
public boolean canScrollVertically() {
return false;
}
});
((DefaultItemAnimator) mTypeRv.getItemAnimator()).setSupportsChangeAnimations(false);
mTypeRv.setAdapter(new SuggestTypeAdapter(this, curType, arrType));
// 意见反馈上传图片列表
mSuggestPicRv.setLayoutManager(new GridLayoutManager(this, 5) {
@Override
public boolean canScrollVertically() {
return false;
}
});
mAdapter = new SuggestPicAdapter(this);
mSuggestPicRv.setAdapter(mAdapter);
SoftInputHidWidgetUtils.assistActivity(this);
if (!TextUtils.isEmpty(suggestContent)) {
mSuggestContentEt.setText(suggestContent);
}
initSuggest(curType);
if (curType == 5 && !TextUtils.isEmpty(suggestContent)) {
mSuggestGameLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
}
String suggestionType = sp.getString("SuggestionType", null);
if (!TextUtils.isEmpty(suggestHintType) && !TextUtils.isEmpty(suggestionType)) {
Gson gson = new Gson();
SuggestionTypeEntity typeEntity = gson.fromJson(suggestionType, SuggestionTypeEntity.class);
if (typeEntity != null) {
switch (suggestHintType) {
case "plugin":
List<String> plugin = typeEntity.getPlugin();
if (plugin != null && plugin.size() > 0) {
showHintDialog(plugin);
}
break;
case "game":
List<String> game = typeEntity.getGame();
if (game != null && game.size() > 0) {
showHintDialog(game);
}
break;
case "libao":
List<String> libao = typeEntity.getLibao();
if (libao != null && libao.size() > 0) {
showHintDialog(libao);
}
break;
case "service":
List<String> service = typeEntity.getService();
if (service != null && service.size() > 0) {
showHintDialog(service);
}
break;
}
}
}
UserInfoEntity userInfo = LoginUtils.getUserInfo(this);
if (userInfo != null && !TextUtils.isEmpty(userInfo.getContact())) {
mSuggestEmailEt.setText(userInfo.getContact());
}
}
private void initSuggest(int type) {
switch (type) {
case 1:
mSuggestContentEt.setHint("请详细描述你遇到的问题... \n ↓↓你还可以上传截图");
mSuggestNewsLinkLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
mSuggestGameLl.setVisibility(View.GONE);
break;
case 2:
mSuggestContentEt.setHint("请详细描述你的建议... \n ↓↓你还可以上传截图");
mSuggestNewsLinkLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
mSuggestGameLl.setVisibility(View.GONE);
break;
case 3:
mSuggestContentEt.setHint("请详细描述闪退之前你所进行的操作... \n ↓↓你还可以上传截图");
mSuggestNewsLinkLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
mSuggestGameLl.setVisibility(View.GONE);
break;
case 4:
mSuggestContentEt.setHint("请写上游戏名字,以及具体遇到的问题... \n ↓↓你还可以上传截图");
mSuggestNewsLinkLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
mSuggestGameLl.setVisibility(View.GONE);
break;
case 5:
mSuggestNewsLinkLl.setVisibility(View.GONE);
mSuggestGameLl.setVisibility(View.VISIBLE);
mSuggestContentEt.setVisibility(View.INVISIBLE);
mSuggestContentEt.setHint("你想收录哪个游戏或游戏版本... \n ↓↓你还可以上传截图");
mSuggestNewsLinkEt.setHint("填写链接(例如游戏的下载地址或介绍页面)");
mSuggestNewsLinkLl.setVisibility(View.VISIBLE);
break;
case 6:
mSuggestContentEt.setHint("简单介绍文章内容,然后在下面填写文章链接 \n ↓↓你还可以上传截图");
mSuggestNewsLinkLl.setVisibility(View.VISIBLE);
mSuggestContentEt.setVisibility(View.VISIBLE);
mSuggestGameLl.setVisibility(View.GONE);
mSuggestNewsLinkEt.setHint("填写文章链接");
break;
}
}
private void showHintDialog(List<String> dialogType) {
final Dialog dialog = new Dialog(SuggestionActivity.this);
LinearLayout container = new LinearLayout(SuggestionActivity.this);
container.setOrientation(LinearLayout.VERTICAL);
container.setBackgroundColor(Color.WHITE);
container.setPadding(0, DisplayUtils.dip2px(SuggestionActivity.this, 12), 0, DisplayUtils.dip2px(SuggestionActivity.this, 12));
for (String s : dialogType) {
final TextView reportTv = new TextView(SuggestionActivity.this);
reportTv.setText(s);
reportTv.setTextSize(17);
reportTv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.title));
reportTv.setBackgroundResource(R.drawable.textview_white_style);
int widthPixels = getResources().getDisplayMetrics().widthPixels;
reportTv.setLayoutParams(new LinearLayout.LayoutParams((widthPixels * 9) / 10,
LinearLayout.LayoutParams.WRAP_CONTENT));
reportTv.setPadding(DisplayUtils.dip2px(SuggestionActivity.this, 20), DisplayUtils.dip2px(SuggestionActivity.this, 12),
0, DisplayUtils.dip2px(SuggestionActivity.this, 12));
container.addView(reportTv);
reportTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
mSuggestContentEt.setText(mSuggestContentEt.getText().toString() + reportTv.getText().toString());
}
});
}
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(container);
dialog.show();
}
@Override
public void loadDone() {
}
@Override
public void loadDone(InstallGameEntity entity) {
if (selectGameDialog != null) {
selectGameDialog.cancel();
}
mSuggestGameLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
mSuggestContentEt.setText("推荐收录:" + entity.getGameName() + "(" + entity.getPackageName() + ", " + entity.getGameVersion() + ")");
}
@Override
public void loadError() {
}
@Override
public void loadEmpty() {
}
@OnClick({R.id.suggest_post_btn, R.id.suggest_select_game, R.id.suggest_game_text})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.suggest_post_btn:
if (TextUtils.isEmpty(mSuggestContentEt.getText().toString())) {
return;
}
CheckLoginUtils.checkLogin(this, new CheckLoginUtils.OnLoggenInListener() {
@Override
public void onLoggedIn() {
String email = mSuggestEmailEt.getText().toString().trim();
String url = mSuggestNewsLinkEt.getText().toString().trim();
if (!TextUtils.isEmpty(url) && !PatternUtils.isUrlAddress(url)) {
Utils.toast(SuggestionActivity.this, "请输入正确的链接");
return;
}
if (TextUtils.isEmpty(email)) {
showConfirmDialog(email);
} else {
postDialog = WaitingDialogFragment.newInstance(getString(R.string.dialog_feedback_doing));
postDialog.show(getSupportFragmentManager(), null);
List<String> fileList = mAdapter.getFileList();
if (fileList != null && fileList.size() > 0) {
postPic(email);
} else {
initPostData(email, null);
}
}
}
});
break;
case R.id.suggest_select_game:
showSelectDialog();
break;
case R.id.suggest_game_text:
mSuggestGameLl.setVisibility(View.GONE);
mSuggestContentEt.setVisibility(View.VISIBLE);
break;
}
}
// 弹出确认对话框
private void showConfirmDialog(final String email) {
DialogUtils.showWarningDialog(this, "温馨提示", "填写联系方式有助于我们更好地一对一解决您的问题,确定不填写吗?",
"直接提交", "我要填写",
new DialogUtils.ConfirmListener() {
@Override
public void onConfirm() {
mSuggestEmailEt.requestFocus();
mSuggestEmailEt.postDelayed(new Runnable() {
@Override
public void run() {
Util_System_Keyboard.showSoftKeyboard(getApplicationContext(), mSuggestEmailEt);
}
}, 300);
}
},
new DialogUtils.CancelListener() {
@Override
public void onCancel() {
postDialog = WaitingDialogFragment.newInstance(getString(R.string.dialog_feedback_doing));
postDialog.show(getSupportFragmentManager(), null);
List<String> fileList = mAdapter.getFileList();
if (fileList != null && fileList.size() > 0) {
postPic(email);
} else {
initPostData(email, null);
}
}
});
}
private void postPic(final String email) {
final JSONArray picArray = new JSONArray();
Observable.create(new Observable.OnSubscribe<JSONObject>() {
@Override
public void call(Subscriber<? super JSONObject> subscriber) {
String path;
int index = 0;
for (String s : mAdapter.getFileList()) {
path = getCacheDir() + File.separator + System.currentTimeMillis() + index + ".jpg";
if (BitmapUtils.savePicture(path, s)) {
subscriber.onNext(FileUtils.uploadFile(Config.API_HOST + "support/upload/img?type=suggestion", path, LoginUtils.getToken(SuggestionActivity.this)));
index++;
} else {
subscriber.onNext(FileUtils.uploadFile(Config.API_HOST + "support/upload/img?type=suggestion", s, LoginUtils.getToken(SuggestionActivity.this)));
}
}
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<JSONObject>() {
@Override
public void onCompleted() {
Utils.log("=========完成");
initPostData(email, picArray);
}
@Override
public void onError(Throwable e) {
if (postDialog != null) {
postDialog.dismissAllowingStateLoss();
}
Utils.toast(SuggestionActivity.this, "上传失败");
Utils.log("=========上传失败" + e.toString());
}
@Override
public void onNext(JSONObject result) {
if (result != null) {
try {
Utils.log("===========" + result);
int statusCode = result.getInt("statusCode");
if (statusCode == HttpURLConnection.HTTP_OK) {
picArray.put(result.getString("img"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void initPostData(String email, JSONArray picArray) {
Map<String, String> params = new HashMap<>();
params.put("message", mSuggestContentEt.getText().toString().trim());
params.put("from", email);
params.put("ghversion", PackageUtils.getVersionName(this));
params.put("channel", AppController.getInstance().getChannel());
params.put("type", android.os.Build.MODEL);
params.put("sdk", String.valueOf(android.os.Build.VERSION.SDK_INT));
params.put("version", android.os.Build.VERSION.RELEASE);
params.put("source", "光环助手");
params.put("imei", Util_System_Phone_State.getDeviceId(this));
if ((curType == 6 || curType == 5) && !TextUtils.isEmpty(mSuggestNewsLinkEt.getText().toString())) {
params.put("url", mSuggestNewsLinkEt.getText().toString().trim());
}
if (curType > 0) {
params.put("suggestion_type", arrType[curType - 1]);
}
if (curType == 3) {
params.put("log", readFromFile());
}
JSONObject jsonObject = new JSONObject(params);
if (picArray != null && picArray.length() > 0) {
try {
jsonObject.put("pic", picArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
RequestBody body = RequestBody.create(MediaType.parse("application/json"),
jsonObject.toString());
sendSuggestion(body);
}
private void sendSuggestion(final RequestBody body) {
RetrofitManager.getApi().postSuggestion(body, LoginUtils.getToken(this))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new JSONObjectResponse() {
@Override
public void onResponse(JSONObject response) {
if (postDialog != null) {
postDialog.dismissAllowingStateLoss();
}
if (response.length() != 0) {
try {
if ("ok".equals(response.getString("status"))) {
toast("感谢您的反馈!");
setResult(0x122);
finish();
} else {
toast("提交失败,请稍后尝试!");
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
toast("提交失败,请稍后尝试!");
}
}
@Override
public void onFailure(HttpException e) {
try {
if (e != null) {
String string = e.response().errorBody().string();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if (postDialog != null) {
postDialog.dismissAllowingStateLoss();
}
toast("提交失败,请检查网络状态");
}
});
}
private void showSelectDialog() {
View view = View.inflate(this, R.layout.dialog_suggest_select_game, null);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dialog_suggest_game_rv);
TextView back = (TextView) view.findViewById(R.id.dialog_suggest_game_back);
ProgressBar pb = (ProgressBar) view.findViewById(R.id.dialog_suggest_game_load);
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
recyclerView.setAdapter(new SuggestSelectGameAdapter(this, pb));
selectGameDialog = new Dialog(this);
selectGameDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
selectGameDialog.setCanceledOnTouchOutside(false);
selectGameDialog.setContentView(view);
selectGameDialog.show();
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectGameDialog.cancel();
}
});
}
@Override
public void onType(int type) {
curType = type;
mSuggestPicRv.postDelayed(new Runnable() {
@Override
public void run() {
//将ScrollView滚动到底
mScrollView.fullScroll(View.FOCUS_DOWN);
}
}, 100);
initSuggest(type);
}
public String readFromFile() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File file = new File(getExternalFilesDir(null).getPath() + "/log");
if (file.isFile()) return "检测log文件夹是文件";
File[] files = file.listFiles();
if (files == null || files.length == 0) return "log文件夹为空" + file.getPath();
File targetFile = files[files.length - 1];
try {
if (!targetFile.exists()) {
targetFile.createNewFile();
return "No File error ";
} else {
InputStream in = new BufferedInputStream(new FileInputStream(targetFile));
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String tmp;
StringBuffer string = new StringBuffer();
while ((tmp = br.readLine()) != null) {
string.append(tmp);
}
br.close();
in.close();
return string.toString();
}
} catch (Exception e) {
return e.toString();
}
} else {
return "SD Card error";
}
}
}