Files
assistant-android/app/src/main/java/com/gh/gamecenter/NewsActivity.java
huangzhuanghua f394fdacdd 集成热更
2016-05-10 15:09:50 +08:00

2716 lines
133 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.gh.gamecenter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.NoConnectionError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.DiskBasedCache;
import com.gh.base.AppController;
import com.gh.base.BaseActivity;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.DeviceUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.GzipUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.MD5Utils;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.TokenUtils;
import com.gh.common.util.Utils;
import com.gh.common.view.BezelImageView;
import com.gh.common.view.DownloadDialog;
import com.gh.common.view.KeyboardLayout;
import com.gh.common.view.KeyboardLayout.OnKeyboardChangedListener;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntry;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.CommentEntity;
import com.gh.gamecenter.entity.DismissEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.NewsDetailsEntity;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.eventbus.EBPWDismiss;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBPutUrl;
import com.gh.gamecenter.eventbus.EBRedDot;
import com.gh.gamecenter.manager.ConcernManager;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tendcloud.tenddata.TCAgent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import de.greenrobot.event.EventBus;
/**
* 文章详情页面 要启动该页面 需要传入一下参数 放入 EssayEntity中传过来 文章 id 文章标题 title 文章发表时间 time
*
* @author 黄壮华
*/
public class NewsActivity extends BaseActivity implements OnClickListener {
private static final String DEFAULT_CACHE_DIR = "volley";
private LinearLayout essaydetails_ll_loading, essaydetails_ll_bottom,
reuse_no_connection, essaydetails_ll_comment;
private NewsDetailsEntity entity;
private TextView actionbar_tv_title, essaydetails_tv_download,
essaydetails_tv_per, essaydetails_tv_comment_content,
essaydetails_tv_comment_send;
private ImageView essaydetails_iv_share;
private ProgressBar essaydetails_progressbar;
private GameEntity gameEntity;
private DownloadEntry downloadEntry;
private RecyclerView essaydetails_rv_show;
private NewsAdapter adapter;
private LinearLayoutManager linearLayoutManager;
private String entrance;
private String newsId;
private long start = 0L;
private int width;
private boolean isSentReport = false;
private boolean isDestroy = false;
private boolean isShowBottom = false;
private boolean isLoading = true;
private boolean isNetworkError = false;
private DismissEntity dismissEntity;
private ArrayMap<String, Long> lastTimeMap;
private ArrayMap<String, String> statusMap;
private ArrayMap<String, Long> timeMap;
private ArrayList<CommentEntity> commentList;
private ArrayMap<String, String> commentFeedbackMap;
private ArrayMap<String, Boolean> fullMap;
private PopupWindow popupWindow;
private ConcernManager concernManager;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (!isDestroy) {
if (msg.what == Constants.CONTINUE_DOWNLOAD_TASK) {
String url = (String) msg.obj;
if (System.currentTimeMillis() - lastTimeMap.get(url) >= 1000) {
DownloadManager.getInstance(NewsActivity.this).resume(
url);
}
} else if (msg.what == Constants.PAUSE_DOWNLOAD_TASK) {
String url = (String) msg.obj;
if (System.currentTimeMillis() - lastTimeMap.get(url) >= 1000) {
DownloadManager.getInstance(NewsActivity.this).pause(
url);
}
} else if (msg.what == Constants.SEND_NEWS_FEEDBACK) {
String key = (String) msg.obj;
if (System.currentTimeMillis() - timeMap.get(key) >= 1000) {
if (msg.arg1 == 0) {
modifyUserNewsFeedbackVolleyCache("up");
modifyNewsFeedback(entity.getId(), "up", msg.arg2);
} else if (msg.arg1 == 1) {
modifyUserNewsFeedbackVolleyCache("down");
modifyNewsFeedback(entity.getId(), "down", msg.arg2);
} else if (msg.arg1 == 2) {
modifyUserNewsFeedbackVolleyCache(null);
cancelNewsFeedback(entity.getId(), msg.arg2);
}
}
} else if (msg.what == Constants.SEND_COMMENT_FEEDBACK) {
String key = (String) msg.obj;
String oldAction = null;
if (key.contains("=")){
int i = key.indexOf("=");
oldAction = key.substring(i + 1);
key = key.substring(0, i);
}
if (System.currentTimeMillis() - timeMap.get(key) >= 1000) {
int index = msg.arg2;
CommentEntity commentEntity = commentList.get(index);
final String id = commentEntity.getId();
if (msg.arg1 == 0) {
modifyUserCommentFeedbackVolleyCache(id, "up");
modifyCommentFeedback(entity.getId(), id, "up", oldAction, index);
} else if (msg.arg1 == 1) {
modifyUserCommentFeedbackVolleyCache(id, "down");
modifyCommentFeedback(entity.getId(), id, "down", oldAction, index);
} else if (msg.arg1 == 2) {
modifyUserCommentFeedbackVolleyCache(id, null);
cancelCommentFeedback(entity.getId(), id, oldAction, index);
}
}
}
}
}
};
private DataWatcher dataWatcher = new DataWatcher() {
@Override
public void onDataChanged(
HashMap<String, DownloadEntry> downloadingEntries) {
if (gameEntity != null && gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
for (Map.Entry<String, DownloadEntry> entry : downloadingEntries
.entrySet()) {
if (url.equals(entry.getValue().getUrl())) {
if (!"pause".equals(statusMap.get(entry.getValue()
.getUrl()))) {
downloadEntry = entry.getValue();
invalidate();
}
break;
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = View.inflate(this, R.layout.activity_essaydetails,
null);
init(contentView);
dismissEntity = new DismissEntity(false);
concernManager = new ConcernManager(getApplicationContext());
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
width = outMetrics.widthPixels - DisplayUtils.dip2px(getApplicationContext(), 73);
RelativeLayout reuse_actionbar = (RelativeLayout) findViewById(R.id.reuse_actionbar);
View share = View.inflate(this, R.layout.reuse_ico, null);
share.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (gameEntity == null) {
toast("分享异常,请稍后再试!");
} else {
String url = "http://news.ghzhushou.com/" + entity.getId() + ".html";
showShare(url, entity.getTitle(), gameEntity.getIcon(), entrance, "新闻");
}
}
});
((ImageView) share.findViewById(R.id.reuse_iv_ico))
.setImageResource(R.drawable.essay_share);
RelativeLayout.LayoutParams rparams1 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rparams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rparams1.addRule(RelativeLayout.CENTER_VERTICAL);
rparams1.rightMargin = DisplayUtils.dip2px(getApplicationContext(), 8);
share.setLayoutParams(rparams1);
reuse_actionbar.addView(share);
View comment = View.inflate(this, R.layout.reuse_ico, null);
comment.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (essaydetails_ll_comment.getVisibility() != View.VISIBLE) {
essaydetails_ll_comment.setVisibility(View.VISIBLE);
essaydetails_ll_bottom.setVisibility(View.GONE);
TranslateAnimation animation = new TranslateAnimation(0, 0,
DisplayUtils.dip2px(getApplicationContext(), 48), 0);
animation.setDuration(500);
essaydetails_ll_comment.startAnimation(animation);
}
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
essaydetails_rv_show.smoothScrollToPosition(3 + moreSize);
}
});
((ImageView) comment.findViewById(R.id.reuse_iv_ico))
.setImageResource(R.drawable.essay_comment);
RelativeLayout.LayoutParams rparams2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rparams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rparams2.addRule(RelativeLayout.CENTER_VERTICAL);
rparams2.rightMargin = DisplayUtils.dip2px(getApplicationContext(), 46);
comment.setLayoutParams(rparams2);
reuse_actionbar.addView(comment);
entrance = (String) getIntent().getExtras().get("entrance");
newsId = getIntent().getStringExtra("newsId");
if (newsId == null) {
entity = (NewsDetailsEntity) getIntent().getExtras().get("entity");
actionbar_tv_title.setText(entity.getType());
}
commentList = new ArrayList<CommentEntity>();
lastTimeMap = new ArrayMap<String, Long>();
statusMap = new ArrayMap<String, String>();
fullMap = new ArrayMap<String, Boolean>();
timeMap = new ArrayMap<String, Long>();
WebView essaydetails_webView = (WebView) findViewById(R.id.essaydetails_webView);
if (NetworkUtils.isWifiConnected(this)) {
essaydetails_webView.setVisibility(View.INVISIBLE);
if (newsId != null) {
essaydetails_webView.loadUrl("http://news.ghzhushou.com/" + newsId + ".html");
} else {
essaydetails_webView.loadUrl("http://news.ghzhushou.com/" + entity.getId() + ".html");
}
} else {
essaydetails_webView.setVisibility(View.GONE);
}
essaydetails_ll_bottom.setOnClickListener(this);
reuse_no_connection.setOnClickListener(this);
essaydetails_tv_download.setOnClickListener(this);
essaydetails_iv_share.setOnClickListener(this);
essaydetails_progressbar.setOnClickListener(this);
essaydetails_tv_per.setOnClickListener(this);
essaydetails_tv_comment_content.setOnClickListener(this);
essaydetails_tv_comment_content
.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
essaydetails_tv_comment_content
.setBackgroundResource(R.drawable.essaydetails_comment_dn);
essaydetails_tv_comment_send.setClickable(true);
essaydetails_tv_comment_send
.setTextColor(0xffffffff);
essaydetails_tv_comment_send
.setBackgroundResource(R.drawable.textview_blue_style);
} else {
essaydetails_tv_comment_content
.setBackgroundResource(R.drawable.essaydetails_comment_up);
essaydetails_tv_comment_send.setClickable(false);
essaydetails_tv_comment_send
.setTextColor(0xff999999);
essaydetails_tv_comment_send
.setBackgroundResource(R.drawable.textview_again_up);
}
int line = essaydetails_tv_comment_content
.getLineCount();
if (line != 0) {
LinearLayout.LayoutParams lparams = (LinearLayout.LayoutParams) essaydetails_tv_comment_content
.getLayoutParams();
if (line == 1) {
lparams.height = DisplayUtils.dip2px(
getApplicationContext(), 34);
} else {
lparams.height = DisplayUtils.dip2px(
getApplicationContext(), 20)
+ (line > 3 ? 3 : line)
* DisplayUtils.dip2px(
getApplicationContext(), 12);
}
essaydetails_tv_comment_content
.setLayoutParams(lparams);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
essaydetails_tv_comment_send.setOnClickListener(this);
essaydetails_tv_comment_send.setClickable(false);
essaydetails_rv_show.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
essaydetails_rv_show.setLayoutManager(linearLayoutManager);
adapter = new NewsAdapter();
essaydetails_rv_show.setAdapter(adapter);
essaydetails_rv_show.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!isDestroy){
if (newState == 0) {
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
if (linearLayoutManager.findLastVisibleItemPosition() >= 2 + moreSize) {
if (essaydetails_ll_comment.getVisibility() != View.VISIBLE) {
essaydetails_ll_comment.setVisibility(View.VISIBLE);
essaydetails_ll_bottom.setVisibility(View.GONE);
TranslateAnimation animation = new TranslateAnimation(0, 0,
DisplayUtils.dip2px(getApplicationContext(), 48), 0);
animation.setDuration(500);
essaydetails_ll_comment.startAnimation(animation);
}
} else {
if (essaydetails_ll_bottom.getVisibility() != View.VISIBLE) {
if (isShowBottom) {
essaydetails_ll_comment.setVisibility(View.GONE);
essaydetails_ll_bottom.setVisibility(View.VISIBLE);
TranslateAnimation animation = new TranslateAnimation(0, 0,
DisplayUtils.dip2px(getApplicationContext(), 48), 0);
animation.setDuration(500);
essaydetails_ll_bottom.startAnimation(animation);
}
}
}
if (isLoading && linearLayoutManager.findLastVisibleItemPosition() == adapter.getItemCount() - 1) {
getComment(commentList.size());
}
}
}
}
});
if (newsId != null) {
getNewDigest(newsId);
} else {
getContent();
}
start = Calendar.getInstance().getTimeInMillis();
if (isShowBottom) {
essaydetails_ll_bottom.setVisibility(View.VISIBLE);
}
View view = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
if (view != null) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
mHits[mHits.length - 1] = SystemClock.uptimeMillis();
if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
essaydetails_rv_show.scrollToPosition(0);
}
}
});
}
}
private void getNewDigest(final String news_id) {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Config.HOST + "v1d45/news/" + news_id + "/digest",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Gson gson = new Gson();
NewsEntity newsEntity = gson.fromJson(
response.toString(), NewsEntity.class);
NewsDetailsEntity essayEntity = new NewsDetailsEntity();
essayEntity.setTitle(newsEntity.getTitle());
essayEntity.setType(newsEntity.getType());
essayEntity.setId(news_id);
entity = essayEntity;
actionbar_tv_title.setText(entity.getType());
getContent();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 无网络连接和访问超时
if (error.getClass().equals(NoConnectionError.class)
|| error.getClass().equals(TimeoutError.class)) {
if (!isDestroy) {
essaydetails_rv_show.setVisibility(View.GONE);
essaydetails_ll_loading.setVisibility(View.GONE);
essaydetails_ll_bottom.setVisibility(View.GONE);
reuse_no_connection.setVisibility(View.VISIBLE);
}
}
}
});
AppController.addToRequestQueue(request, NewsActivity.class);
}
private long[] mHits = new long[2];
@Override
public void onClick(View v) {
if (v == essaydetails_tv_download) {
if (gameEntity != null && !gameEntity.getApk().isEmpty()) {
if (NetworkUtils.isWifiConnected(this)) {
if (gameEntity.getApk().size() == 1) {
if (essaydetails_tv_download.getText().toString()
.contains("启动")) {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("版本", gameEntity.getApk().get(0)
.getPlatform());
TCAgent.onEvent(NewsActivity.this, "游戏启动",
gameEntity.getName(), kv);
PackageUtils.launchApplicationByPackageName(
getApplicationContext(), gameEntity
.getApk().get(0).getPackageName());
} else {
ApkEntity apkEntity = gameEntity.getApk().get(0);
String msg = FileUtils.isCanDownload(apkEntity
.getSize());
if (TextUtils.isEmpty(msg)) {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("版本", apkEntity.getPlatform());
kv.put("状态", "下载开始");
TCAgent.onEvent(NewsActivity.this, "游戏下载",
gameEntity.getName(), kv);
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put("版本", apkEntity.getPlatform());
kv2.put("状态", "下载开始");
kv2.put("位置", entrance + "-文章详情-开始");
TCAgent.onEvent(NewsActivity.this, "游戏下载位置",
gameEntity.getName(), kv2);
Map<String, Object> kv3 = new HashMap<String, Object>();
kv3.put(entrance, "下载数");
kv3.put(entrance, "下载开始");
TCAgent.onEvent(NewsActivity.this, "应用数据",
gameEntity.getName(), kv3);
Map<String, Object> map = new HashMap<String, Object>();
map.put("game", gameEntity.getName());
map.put("method", "正常");
map.put("platform",
PlatformUtils.getInstance(
getApplicationContext())
.getPlatformName(
gameEntity.getApk()
.get(0)
.getPlatform()));
map.put("status", "开始");
map.put("location", "新闻详情:" + entity.getTitle());
map.put("from", entrance);
map.put("network",
NetworkUtils.getConnectedType(this));
map.put("createdOn",
System.currentTimeMillis() / 1000);
DataCollectionManager.onEvent(this, "download",
map);
DownloadEntry entry = new DownloadEntry();
entry.setUrl(apkEntity.getUrl());
entry.setName(gameEntity.getName());
entry.setPath(FileUtils.getDownloadPath(
NewsActivity.this,
MD5Utils.getContentMD5(gameEntity
.getName()
+ "_"
+ System.currentTimeMillis())
+ ".apk"));
HashMap<String, String> meta = new HashMap<String, String>();
meta.put("ETag", apkEntity.getEtag());
meta.put("icon", gameEntity.getIcon());
meta.put("platform", apkEntity.getPlatform());
meta.put("gameId", gameEntity.getId());
meta.put("entrance", entrance + "-文章详情");
meta.put("location",
"新闻详情:" + entity.getTitle());
entry.setMeta(meta);
DownloadManager.getInstance(
getApplicationContext()).add(entry);
EventBus.getDefault().post(new EBRedDot(1));
essaydetails_tv_download
.setVisibility(View.GONE);
essaydetails_progressbar
.setVisibility(View.VISIBLE);
essaydetails_tv_per.setVisibility(View.VISIBLE);
essaydetails_progressbar.setProgress(0);
essaydetails_tv_per.setText("0.0%");
statusMap.put(entry.getUrl(), "downloading");
} else {
toast(msg);
}
}
} else {
if (!dismissEntity.isShow()) {
dismissEntity.setShow(true);
DownloadDialog.getInstance(NewsActivity.this)
.showPopupWindow(v, gameEntity,
entrance + "-文章详情", handler,
lastTimeMap, statusMap,
"新闻详情:" + entity.getTitle());
}
}
} else {
final Dialog dialog = new Dialog(this);
View view = View.inflate(this,
R.layout.search_history_delete_dialog, null);
TextView title = (TextView) view
.findViewById(R.id.delete_dialog_title);
title.setText("警告");
TextView content = (TextView) view
.findViewById(R.id.delete_dialog_message);
content.setText("您当前的网络为2G/3G/4G下载将会消耗移动流量是否继续下载");
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("继续");
confirem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (gameEntity.getApk().size() == 1) {
if (essaydetails_tv_download.getText()
.toString().contains("启动")) {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("版本", gameEntity.getApk().get(0)
.getPlatform());
TCAgent.onEvent(NewsActivity.this, "游戏启动",
gameEntity.getName(), kv);
PackageUtils
.launchApplicationByPackageName(
getApplicationContext(),
gameEntity.getApk().get(0)
.getPackageName());
} else {
ApkEntity apkEntity = gameEntity.getApk()
.get(0);
String msg = FileUtils
.isCanDownload(apkEntity.getSize());
if (TextUtils.isEmpty(msg)) {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("版本", apkEntity.getPlatform());
kv.put("状态", "下载开始");
TCAgent.onEvent(NewsActivity.this,
"游戏下载", gameEntity.getName(),
kv);
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put("版本", apkEntity.getPlatform());
kv2.put("状态", "下载开始");
kv2.put("位置", entrance + "-文章详情-开始");
TCAgent.onEvent(NewsActivity.this,
"游戏下载位置", gameEntity.getName(),
kv2);
Map<String, Object> map = new HashMap<String, Object>();
map.put("game", gameEntity.getName());
map.put("method", "正常");
map.put("platform",
PlatformUtils
.getInstance(
getApplicationContext())
.getPlatformName(
gameEntity
.getApk()
.get(0)
.getPlatform()));
map.put("status", "开始");
map.put("location",
"新闻详情:" + entity.getTitle());
map.put("from", entrance);
map.put("network",
NetworkUtils
.getConnectedType(NewsActivity.this));
map.put("createdOn",
System.currentTimeMillis() / 1000);
DataCollectionManager.onEvent(
NewsActivity.this, "download",
map);
DownloadEntry entry = new DownloadEntry();
entry.setUrl(apkEntity.getUrl());
entry.setName(gameEntity.getName());
entry.setPath(FileUtils
.getDownloadPath(
NewsActivity.this,
MD5Utils.getContentMD5(gameEntity
.getName()
+ "_"
+ System.currentTimeMillis())
+ ".apk"));
HashMap<String, String> meta = new HashMap<String, String>();
meta.put("ETag", apkEntity.getEtag());
meta.put("icon", gameEntity.getIcon());
meta.put("platform",
apkEntity.getPlatform());
meta.put("gameId", gameEntity.getId());
meta.put("entrance", entrance + "-文章详情");
meta.put("location",
"新闻详情:" + entity.getTitle());
entry.setMeta(meta);
DownloadManager.getInstance(
getApplicationContext()).add(
entry);
EventBus.getDefault().post(
new EBRedDot(1));
essaydetails_tv_download
.setVisibility(View.GONE);
essaydetails_progressbar
.setVisibility(View.VISIBLE);
essaydetails_tv_per
.setVisibility(View.VISIBLE);
essaydetails_progressbar.setProgress(0);
essaydetails_tv_per.setText("0.0%");
statusMap.put(entry.getUrl(),
"downloading");
} else {
toast(msg);
}
}
} else {
if (!dismissEntity.isShow()) {
dismissEntity.setShow(true);
DownloadDialog.getInstance(
NewsActivity.this).showPopupWindow(
v, gameEntity, entrance + "-文章详情",
handler, lastTimeMap, statusMap,
"新闻详情:" + entity.getTitle());
}
}
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
} else {
toast("稍等片刻~!游戏正在上传中...");
}
} else if (v == essaydetails_iv_share) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("location", "分享");
map.put("createOn", System.currentTimeMillis() / 1000);
map.put("news", entity.getTitle());
map.put("page", "新闻详情");
DataCollectionManager.onEvent(this, "click-item", map);
String url = "http://news.ghzhushou.com/" + entity.getId()
+ ".html";
showShare(url, entity.getTitle(), gameEntity.getIcon(), entrance,
"新闻");
} else if (v == essaydetails_progressbar || v == essaydetails_tv_per) {
String str = essaydetails_tv_per.getText().toString();
if ("继续".equals(str)) {
statusMap.put(downloadEntry.getUrl(), "downloading");
essaydetails_tv_per.setText(downloadEntry.getPercent() + "%");
Message msg = Message.obtain();
msg.what = Constants.CONTINUE_DOWNLOAD_TASK;
msg.obj = downloadEntry.getUrl();
lastTimeMap.put(downloadEntry.getUrl(),
System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
} else if ("安装".equals(str)) {
String path = downloadEntry.getPath();
PackageManager manager = new PackageManager(
getApplicationContext());
if (manager.launchSetup(path)) {
startActivity(PackageUtils.getInstallIntent(path));
} else {
DialogUtils.showDialog(NewsActivity.this, path);
}
} else {
statusMap.put(downloadEntry.getUrl(), "pause");
essaydetails_tv_per.setText("继续");
Message msg = Message.obtain();
msg.what = Constants.PAUSE_DOWNLOAD_TASK;
msg.obj = downloadEntry.getUrl();
lastTimeMap.put(downloadEntry.getUrl(),
System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
}
} else if (v == reuse_no_connection) {
essaydetails_rv_show.setVisibility(View.VISIBLE);
essaydetails_ll_loading.setVisibility(View.VISIBLE);
essaydetails_ll_bottom.setVisibility(View.VISIBLE);
reuse_no_connection.setVisibility(View.GONE);
handler.postDelayed(runnable, 1000);
} else if (v == essaydetails_tv_comment_content) {
showCommentDialog(v, essaydetails_tv_comment_content.getText(),
essaydetails_tv_comment_content.getLineCount());
} else if (v == essaydetails_tv_comment_send) {
sendComment(essaydetails_tv_comment_content.getText());
}
}
Runnable runnable = new Runnable() {
@Override
public void run() {
if (newsId != null) {
getNewDigest(newsId);
} else {
getContent();
}
}
};
private void getContent() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Config.HOST + "v1d45/news/" + entity.getId() + "/detail",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (!isDestroy) {
Gson gson = new Gson();
NewsDetailsEntity essayEntity = gson.fromJson(response.toString(), NewsDetailsEntity.class);
essayEntity.setTitle(entity.getTitle());
if (entity.getTime() != null) {
essayEntity.setTime(entity.getTime());
}
essayEntity.setType(entity.getType());
if (entity.getId() != null) {
essayEntity.setId(entity.getId());
}
entity = essayEntity;
adapter.notifyDataSetChanged();
// 获取相关推荐
getNewsMore();
// 获取游戏数据
getGameDetails();
// 获取文章反馈数据
getNewsFeedback();
// 获取用户反馈数据
getUserFeedback();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log(error.toString());
if (error.networkResponse != null) {
Utils.log(new String(error.networkResponse.data));
}
// 无网络连接和访问超时
if (error.getClass().equals(NoConnectionError.class)
|| error.getClass().equals(TimeoutError.class)) {
if (!isDestroy) {
essaydetails_rv_show.setVisibility(View.GONE);
essaydetails_ll_loading.setVisibility(View.GONE);
essaydetails_ll_bottom.setVisibility(View.GONE);
reuse_no_connection.setVisibility(View.VISIBLE);
}
}
}
});
AppController.addToRequestQueue(request, NewsActivity.class);
}
private void getNewsMore() {
JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
TimestampUtils.addTimestamp(Config.HOST + "v1d45/news/"
+ entity.getId() + "/suggestion", Constants.NEWS_CD),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Utils.log(response);
if (!isDestroy) {
Type listType = new TypeToken<ArrayList<NewsEntity>>() {}.getType();
Gson gson = new Gson();
List<NewsEntity> list = gson.fromJson(
response.toString(), listType);
// 去除与当前文章重复的文章
for (int i = 0, size = list.size(); i < size; i++) {
if (entity.getId().equals(list.get(i).getId())) {
list.remove(i);
break;
}
}
List<NewsEntity> more = new ArrayList<NewsEntity>();
// TODO 随机三篇文章
int[] index = new int[list.size() > 3 ? 3 : list
.size()];
Random random = new Random(System
.currentTimeMillis());
for (int i = 0; i < index.length; i++) {
if (i == 0) {
index[i] = random.nextInt(list.size());
} else {
index[i] = random(random, index, i,
list.size());
}
}
for (int i = 0; i < index.length; i++) {
more.add(list.get(index[i]));
}
entity.setMore(more);
adapter.notifyItemChanged(0);
adapter.notifyItemRangeInserted(1, entity.getMore().size());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log(error);
}
});
AppController.addToRequestQueue(request, NewsActivity.class);
}
private int random(Random random, int[] index, int i, int size) {
int seed = random.nextInt(size);
for (int j = 0; j < i; j++) {
if (index[j] == seed) {
return random(random, index, i, size);
}
}
return seed;
}
private void getGameDetails() {
JsonObjectExtendedRequest gameRequest = new JsonObjectExtendedRequest(
TimestampUtils.addTimestamp(Config.HOST + "v1d45/game/"
+ entity.getGame() + "/news_digest", Constants.GAME_CD),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (!isDestroy) {
processingGameData(response.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.addToRequestQueue(gameRequest, NewsActivity.class);
}
private void processingGameData(String data) {
Gson gson = new Gson();
gameEntity = gson.fromJson(data, GameEntity.class);
boolean isInstalled = false;
if (gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1
&& PackageManager.isInstalled(gameEntity.getApk().get(0)
.getPackageName())) {
isInstalled = true;
}
if (TextUtils.isEmpty(gameEntity.getDownloadAddWord())) {
essaydetails_tv_download.setVisibility(View.VISIBLE);
essaydetails_progressbar.setVisibility(View.GONE);
essaydetails_tv_per.setVisibility(View.GONE);
if (isInstalled) {
essaydetails_tv_download.setText("启动《" + gameEntity.getName() + "");
} else {
essaydetails_tv_download.setText("下载《" + gameEntity.getName() + "");
}
} else {
essaydetails_tv_download.setVisibility(View.VISIBLE);
essaydetails_progressbar.setVisibility(View.GONE);
essaydetails_tv_per.setVisibility(View.GONE);
if (isInstalled) {
essaydetails_tv_download.setText("启动《" + gameEntity.getName() + "" + gameEntity.getDownloadAddWord());
} else {
essaydetails_tv_download.setText("下载《" + gameEntity.getName() + "" + gameEntity.getDownloadAddWord());
}
}
if (gameEntity.getApk() == null) {
essaydetails_ll_bottom.setVisibility(View.GONE);
isShowBottom = false;
} else {
for (int i = 0, size = gameEntity.getApk().size(); i < size; i++) {
String packageName = gameEntity.getApk().get(i).getPackageName();
if (PackageManager.isInstalled(packageName)
|| getPackageName().equals(packageName)) {
essaydetails_ll_bottom.setVisibility(View.GONE);
essaydetails_ll_comment.setVisibility(View.VISIBLE);
TranslateAnimation animation = new TranslateAnimation(0, 0,
DisplayUtils.dip2px(getApplicationContext(), 48), 0);
animation.setDuration(500);
essaydetails_ll_comment.startAnimation(animation);
isShowBottom = false;
break;
} else if (i == size - 1) {
isShowBottom = true;
essaydetails_ll_bottom.setVisibility(View.VISIBLE);
TranslateAnimation animation = new TranslateAnimation(0, 0,
DisplayUtils.dip2px(getApplicationContext(), 48), 0);
animation.setDuration(500);
essaydetails_ll_bottom.startAnimation(animation);
}
}
}
adapter.notifyItemChanged(0);
}
private void getNewsFeedback() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/feedback", Constants.COMMENT_CD),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log("getNewsFeedback = " + response.toString());
if (!isDestroy) {
try {
entity.setUp(response.getLong("up"));
entity.setDown(response.getLong("down"));
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
adapter.notifyItemChanged(1 + moreSize);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.addToRequestQueue(request, NewsActivity.class);
}
private void getUserFeedback() {
new Thread() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/user/feedback",
Constants.COMMENT_CD),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log("getUserFeedback success = " + response.toString());
if (!isDestroy) {
try {
String action = response.getJSONObject("news").getString("action");
if (!TextUtils.isEmpty(action)) {
entity.setAction(action);
}
JSONArray comment = response.getJSONArray("comment");
if (comment.length() != 0) {
commentFeedbackMap = new ArrayMap<String, String>();
for (int i = 0; i < comment.length(); i++) {
JSONObject jsonObject = comment.getJSONObject(i);
commentFeedbackMap.put(
jsonObject.getString("id"),
jsonObject.getString("action"));
}
}
adapter.notifyItemRangeChanged(1, adapter.getItemCount() - 1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log("getUserFeedback error = " + error.toString());
if (error.networkResponse != null) {
Utils.log("getUserFeedback error = " + new String(error.networkResponse.data));
}
}
});
String token = TokenUtils.getToken(NewsActivity.this);
request.addHeader("Auth", token);
AppController.addToRequestQueue(request, NewsActivity.class);
}
}.start();
}
private void showSuccessDialog() {
final Dialog dialog = new Dialog(this);
View view = View.inflate(this, R.layout.gamedetails_attention_dialog,
null);
TextView title = (TextView) view.findViewById(R.id.dialog_title);
title.setText("关注成功");
TextView confirm = (TextView) view.findViewById(R.id.dialog_confirm);
confirm.setText("我知道了");
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView message = (TextView) view.findViewById(R.id.dialog_message);
message.setText("游戏的最新动态消息会优先提醒您,包括攻略、资讯、开服信息、开测信息以及最新的插件。");
view.findViewById(R.id.dialog_rl_cancel).setVisibility(View.GONE);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
private void showCancelDialog(final TextView attention) {
final Dialog dialog = new Dialog(this);
View view = View.inflate(this, R.layout.gamedetails_attention_dialog,
null);
TextView title = (TextView) view.findViewById(R.id.dialog_title);
title.setText("取消关注");
TextView cancel = (TextView) view.findViewById(R.id.dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView message = (TextView) view.findViewById(R.id.dialog_message);
Spanned content = Html
.fromHtml("取消关注游戏后,您将无法及时收到游戏的<font color='#ff0000'>攻略</font>、<font color='#ff0000'>资讯</font>等最新动态提醒,您确定取消吗?");
message.setText(content);
view.findViewById(R.id.dialog_rl_confirm).setVisibility(View.VISIBLE);
view.findViewById(R.id.dialog_confirm).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("状态", "取消关注");
TCAgent.onEvent(NewsActivity.this, "游戏关注",
gameEntity.getName(), kv);
Map<String, Object> map = new HashMap<String, Object>();
map.put("game", gameEntity.getName());
map.put("type", "关注");
map.put("createdOn", System.currentTimeMillis() / 1000);
DataCollectionManager.onEvent(NewsActivity.this,
"concern", map);
concernManager.deleteConcern(gameEntity.getId());
dialog.dismiss();
attention.setText("关注");
attention
.setBackgroundResource(R.drawable.textview_red_style);
attention.setTextColor(0xffffffff);
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
public class JsInterface {
private Context context;
private ArrayList<String> imgs = new ArrayList<String>();
public JsInterface(Context context) {
this.context = context;
}
@JavascriptInterface
public void openImage(String url) {
int current = 0;
for (int i = 0, size = imgs.size(); i < size; i++) {
if (url.equals(imgs.get(i))) {
current = i;
}
}
Intent checkIntent = new Intent(context, ViewImageActivity.class);
checkIntent.putExtra("urls", imgs);
checkIntent.putExtra("current", current);
checkIntent.putExtra("ScaleType", "FIT_CENTER");
context.startActivity(checkIntent);
}
@JavascriptInterface
public void addImage(String url) {
if (!imgs.contains(url)) {
imgs.add(url);
}
}
@JavascriptInterface
public void skip(String id, String type) {
if ("game".equals(type)) {
Intent intent = new Intent(NewsActivity.this,
GameDetailsActivity.class);
intent.putExtra("gameId", id);
intent.putExtra("entrance", entrance);
startActivity(intent);
} else if ("news".equals(type)) {
Intent intent = new Intent(NewsActivity.this,
NewsActivity.class);
intent.putExtra("newsId", id);
intent.putExtra("entrance", entrance);
startActivity(intent);
}
}
}
private class NewsViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
private LinearLayout essaydetails_ll_top;
private View essaydetails_line;
private ImageView essaydetails_icon;
private TextView essaydetails_name, essaydetails_info,
essaydetails_attention, essaydetails_title, essaydetails_time,
essaydetails_author, essaydetails_tv_more;
private WebView essaydetails_wv_content;
private LinearLayout news_item_ll;
private TextView news_type, news_title;
private LinearLayout essaydetails_ll_liked, essaydetails_ll_unliked;
private ImageView essaydetails_iv_liked, essaydetails_iv_unliked;
private TextView essaydetails_tv_liked, essaydetails_tv_unliked;
private BezelImageView comment_item_iv_icon;
private LinearLayout comment_item_ll_full;
private TextView comment_item_tv_username, comment_item_tv_time,
comment_item_tv_content, comment_item_tv_like,
comment_item_tv_unlike;
private ProgressBar footerview_progressbar;
private TextView footerview_tv_loading;
private View rootView;
public NewsViewHolder(View view, int viewType) {
super(view);
if (viewType == 0) {
essaydetails_ll_top = (LinearLayout) view.findViewById(R.id.essaydetails_ll_top);
essaydetails_ll_top.setOnClickListener(this);
essaydetails_line = view.findViewById(R.id.essaydetails_line);
essaydetails_icon = (ImageView) view.findViewById(R.id.essaydetails_icon);
essaydetails_name = (TextView) view.findViewById(R.id.essaydetails_name);
essaydetails_info = (TextView) view.findViewById(R.id.essaydetails_info);
essaydetails_attention = (TextView) view.findViewById(R.id.essaydetails_attention);
essaydetails_attention.setOnClickListener(this);
essaydetails_title = (TextView) view.findViewById(R.id.essaydetails_title);
essaydetails_time = (TextView) view.findViewById(R.id.essaydetails_time);
essaydetails_author = (TextView) view.findViewById(R.id.essaydetails_author);
essaydetails_wv_content = (WebView) view.findViewById(R.id.essaydetails_wv_content);
essaydetails_tv_more = (TextView) view.findViewById(R.id.essaydetails_tv_more);
} else if (viewType == 1) {
news_type = (TextView) view.findViewById(R.id.news_type);
news_title = (TextView) view.findViewById(R.id.news_title);
news_item_ll = (LinearLayout) view.findViewById(R.id.news_item_ll);
} else if (viewType == 2) {
essaydetails_ll_liked = (LinearLayout) view.findViewById(R.id.essaydetails_ll_liked);
essaydetails_ll_liked.setOnClickListener(this);
essaydetails_ll_unliked = (LinearLayout) view.findViewById(R.id.essaydetails_ll_unliked);
essaydetails_ll_unliked.setOnClickListener(this);
essaydetails_iv_liked = (ImageView) view.findViewById(R.id.essaydetails_iv_liked);
essaydetails_iv_unliked = (ImageView) view.findViewById(R.id.essaydetails_iv_unliked);
essaydetails_tv_liked = (TextView) view.findViewById(R.id.essaydetails_tv_liked);
essaydetails_tv_unliked = (TextView) view.findViewById(R.id.essaydetails_tv_unliked);
} else if (viewType == 3) {
comment_item_iv_icon = (BezelImageView) view.findViewById(R.id.comment_item_iv_icon);
comment_item_ll_full = (LinearLayout) view.findViewById(R.id.comment_item_ll_full);
comment_item_tv_username = (TextView) view.findViewById(R.id.comment_item_tv_username);
comment_item_tv_content = (TextView) view.findViewById(R.id.comment_item_tv_content);
comment_item_tv_time = (TextView) view.findViewById(R.id.comment_item_tv_time);
comment_item_tv_like = (TextView) view.findViewById(R.id.comment_item_tv_like);
comment_item_tv_unlike = (TextView) view.findViewById(R.id.comment_item_tv_unlike);
} else if (viewType == 4) {
footerview_progressbar = (ProgressBar) view.findViewById(R.id.footerview_progressbar);
footerview_tv_loading = (TextView) view.findViewById(R.id.footerview_tv_loading);
rootView = view;
}
}
@Override
public void onClick(View v) {
if (v == essaydetails_ll_liked) {
Message msg = Message.obtain();
msg.what = Constants.SEND_NEWS_FEEDBACK;
if (entity.getAction() != null) {
if ("up".equals(entity.getAction())) {
entity.setAction(null);
entity.setUp(entity.getUp() - 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(1);
} else {
adapter.notifyItemChanged(1 + entity.getMore().size());
}
msg.arg1 = 2;
msg.arg2 = 1;
msg.obj = "CancelNewsLike";
timeMap.put("CancelNewsLike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
return;
} else if ("down".equals(entity.getAction())) {
entity.setDown(entity.getDown() - 1);
msg.arg2 = 2;
}
} else {
msg.arg2 = 0;
}
entity.setAction("up");
entity.setUp(entity.getUp() + 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(1);
} else {
adapter.notifyItemChanged(1 + entity.getMore().size());
}
msg.arg1 = 0;
msg.obj = "SendNewsLike";
timeMap.put("SendNewsLike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
} else if (v == essaydetails_ll_unliked) {
Message msg = Message.obtain();
msg.what = Constants.SEND_NEWS_FEEDBACK;
if (entity.getAction() != null) {
if ("down".equals(entity.getAction())) {
entity.setAction(null);
entity.setDown(entity.getDown() - 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(1);
} else {
adapter.notifyItemChanged(1 + entity.getMore().size());
}
msg.arg1 = 2;
msg.arg2 = 2;
msg.obj = "CancelNewsLike";
timeMap.put("CancelNewsLike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
return;
} else if ("up".equals(entity.getAction())) {
entity.setUp(entity.getUp() - 1);
msg.arg2 = 1;
}
} else {
msg.arg2 = 0;
}
entity.setAction("down");
entity.setDown(entity.getDown() + 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(1);
} else {
adapter.notifyItemChanged(1 + entity.getMore().size());
}
msg.arg1 = 1;
msg.obj = "SendNewsUnlike";
timeMap.put("SendNewsUnlike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
} else if (v == essaydetails_ll_top) {
Intent intent = new Intent(NewsActivity.this,
GameDetailsActivity.class);
intent.putExtra("gameId", gameEntity.getId());
intent.putExtra("entrance", entrance);
startActivity(intent);
} else if (v == essaydetails_attention) {
if ("关注".equals(essaydetails_attention.getText().toString())) {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("状态", "关注");
TCAgent.onEvent(NewsActivity.this, "游戏关注", gameEntity.getName(), kv);
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put("点击", "关注");
TCAgent.onEvent(NewsActivity.this, "插件数据", gameEntity.getName(), kv2);
Map<String, Object> map = new HashMap<String, Object>();
map.put("game", gameEntity.getName());
map.put("type", "关注");
map.put("createdOn", System.currentTimeMillis() / 1000);
DataCollectionManager.onEvent(NewsActivity.this, "concern", map);
concernManager.addByEntity(gameEntity);
essaydetails_attention.setText("取消关注");
essaydetails_attention.setBackgroundResource(R.drawable.border_red_bg);
essaydetails_attention.setTextColor(0xffbc2132);
showSuccessDialog();
} else {
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put("点击", "取消关注");
TCAgent.onEvent(NewsActivity.this, "插件数据", gameEntity.getName(), kv2);
showCancelDialog(essaydetails_attention);
}
}
}
}
private class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> {
@Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == 0) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.essaydetails_item_top, parent, false);
} else if (viewType == 1) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.essaydetails_more_news_item, parent, false);
} else if (viewType == 2) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.essaydetails_comment_evaluate, parent, false);
} else if (viewType == 3) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.essaydetails_comment_item, parent, false);
} else if (viewType == 4) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.refresh_footerview, parent, false);
} else {
RelativeLayout relativeLayout = new RelativeLayout(NewsActivity.this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(getApplicationContext(), 48));
relativeLayout.setLayoutParams(params);
view = relativeLayout;
}
return new NewsViewHolder(view, viewType);
}
@Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
if (position == 0) {
if (gameEntity != null && !gameEntity.getName().contains("光环助手")) {
holder.essaydetails_ll_top.setVisibility(View.VISIBLE);
holder.essaydetails_line.setVisibility(View.VISIBLE);
ImageUtils.getInstance(getApplicationContext()).displayFile(gameEntity.getIcon(), holder.essaydetails_icon);
holder.essaydetails_name.setText(gameEntity.getName());
if (concernManager.isConcern(gameEntity.getId())) {
holder.essaydetails_attention.setText("取消关注");
holder.essaydetails_attention.setBackgroundResource(R.drawable.border_red_bg);
holder.essaydetails_attention.setTextColor(0xffbc2132);
} else {
holder.essaydetails_attention.setText("关注");
holder.essaydetails_attention.setBackgroundResource(R.drawable.textview_red_style);
holder.essaydetails_attention.setTextColor(0xffffffff);
}
if (gameEntity.getApk() != null && !gameEntity.getApk().isEmpty()) {
for (int i = 0, size = gameEntity.getApk().size(); i < size; i++) {
ApkEntity apkEntity = gameEntity.getApk().get(i);
if ("9u".equals(apkEntity.getPlatform())) {
holder.essaydetails_info.setText("V" + apkEntity.getVersion() + " | " + apkEntity.getSize());
break;
}
if (i == size - 1) {
holder.essaydetails_info.setText("V" + apkEntity.getVersion() + " | " + apkEntity.getSize());
}
}
}
} else {
holder.essaydetails_ll_top.setVisibility(View.GONE);
holder.essaydetails_line.setVisibility(View.GONE);
}
holder.essaydetails_title.setText(entity.getTitle());
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
try {
long today = format.parse(format.format(new Date())).getTime();
long day = Long.valueOf(entity.getTime() + "000");
if (day >= today && day < today + 86400 * 1000) {
format.applyPattern("HH:mm");
holder.essaydetails_time.setText("今天 " + format.format(day));
} else if (day >= today - 86400 * 1000 && day < today) {
format.applyPattern("HH:mm");
holder.essaydetails_time.setText("昨天 " + format.format(day));
} else {
format.applyPattern("yyyy年MM月dd日 HH:mm");
holder.essaydetails_time .setText(format.format(day));
}
} catch (ParseException e) {
e.printStackTrace();
format.applyPattern("yyyy年MM月dd日 HH:mm");
holder.essaydetails_time.setText(format.format(Long.valueOf(entity.getTime() + "000")));
}
if (entity.getAuthor() != null) {
holder.essaydetails_author.setText(entity.getAuthor());
}
if (holder.essaydetails_wv_content.getTag() == null) {
holder.essaydetails_wv_content.addJavascriptInterface(new JsInterface(NewsActivity.this), "imagelistener");
WebSettings webSettings = holder.essaydetails_wv_content.getSettings();
webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setJavaScriptEnabled(true);
holder.essaydetails_wv_content.loadDataWithBaseURL(null, entity.getContent(), "text/html", "utf-8", null);
holder.essaydetails_wv_content .setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view,
String url) {
view.loadUrl("javascript:(function(){"
+ "var imgs = document.getElementsByTagName(\"img\");"
+ "for(var i = 0; i < imgs.length - 1; i++) {"
+ " window.imagelistener.addImage(imgs[i].src);"
+ "}"
+ "for(var i = 0; i < imgs.length - 1; i++) {"
+ " imgs[i].onclick = function() {"
+ " window.imagelistener.openImage(this.src);"
+ " }"
+ "}"
+ "var as = document.getElementsByTagName(\"a\");"
+ "for(var i = 0; i < as.length; i++) {"
+ " as[i].onclick = function() {"
+ " window.imagelistener.skip(this.id, this.type);"
+ " }"
+ "}"
+ "})()");
super.onPageFinished(view, url);
if (essaydetails_ll_loading != null) {
essaydetails_ll_loading.setVisibility(View.GONE);
essaydetails_rv_show.setVisibility(View.VISIBLE);
}
}
});
holder.essaydetails_wv_content.setTag("show");
}
if (entity.getMore() != null && entity.getMore().size() != 0) {
holder.essaydetails_tv_more.setVisibility(View.VISIBLE);
} else {
holder.essaydetails_tv_more.setVisibility(View.GONE);
}
} else if (entity.getMore() != null && position >= 1 && position < 1 + entity.getMore().size()) {
final NewsEntity newsEntity = entity.getMore().get(position - 1);
holder.news_type.setBackgroundResource(NewsUtils
.getDrawableIdByType(newsEntity.getType()));
holder.news_type.setText(newsEntity.getType());
holder.news_title.setText(newsEntity.getTitle());
holder.news_item_ll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(NewsActivity.this,
NewsActivity.class);
intent.putExtra("newsId", newsEntity.getId());
intent.putExtra("entrance", entrance);
startActivity(intent);
}
});
} else if ((entity.getMore() == null && position == 1)
|| (entity.getMore() != null && position == 1 + entity.getMore().size())) {
holder.essaydetails_ll_liked.setBackgroundResource(R.drawable.essay_liked_style);
holder.essaydetails_ll_unliked.setBackgroundResource(R.drawable.essay_unliked_style);
holder.essaydetails_iv_liked.setImageResource(R.drawable.essay_like_style);
ColorStateList colorStateList = getResources().getColorStateList(R.color.essay_text_style);
holder.essaydetails_tv_liked.setTextColor(colorStateList);
holder.essaydetails_iv_unliked.setImageResource(R.drawable.essay_unlike_style);
if (entity.getAction() != null) {
if ("up".equals(entity.getAction())) {
holder.essaydetails_ll_liked.setBackgroundResource(R.drawable.essay_liked_dn);
holder.essaydetails_iv_liked.setImageResource(R.drawable.essay_like_dn);
holder.essaydetails_tv_liked.setTextColor(0xFFFFFFFF);
} else if ("down".equals(entity.getAction())) {
holder.essaydetails_ll_unliked.setBackgroundResource(R.drawable.essay_unliked_dn);
holder.essaydetails_iv_unliked.setImageResource(R.drawable.essay_unlike_dn);
}
}
holder.essaydetails_tv_liked.setText(entity.getUp() + "");
holder.essaydetails_tv_unliked.setText(entity.getDown() + "");
} else if ((entity.getMore() == null && !commentList.isEmpty()
&& position >= 2 && position < 2 + commentList.size())
|| (entity.getMore() != null && !commentList.isEmpty()
&& position >= 2 + entity.getMore().size() && position < 2
+ entity.getMore().size() + commentList.size())) {
final int index;
if (entity.getMore() != null) {
index = position - 2 - entity.getMore().size();
} else {
index = position - 2;
}
final CommentEntity commentEntity = commentList.get(index);
ImageUtils.getInstance(getApplicationContext()).display(
commentEntity.getUser().getIcon(),
holder.comment_item_iv_icon,
R.drawable.default_user_icon);
holder.comment_item_tv_username.setText(commentEntity.getUser().getName());
holder.comment_item_tv_content.setText(commentEntity.getContent().replaceAll("\n", " "));
Boolean b = fullMap.get(commentEntity.getId());
if (b != null && b) {
holder.comment_item_tv_content.setMaxLines(Integer.MAX_VALUE);
holder.comment_item_ll_full.setVisibility(View.GONE);
} else {
holder.comment_item_tv_content.setMaxLines(4);
holder.comment_item_tv_content.setEllipsize(TruncateAt.END);
if (holder.comment_item_tv_content.getPaint()
.measureText(holder.comment_item_tv_content.getText().toString())
- 4 * width > 0) {
holder.comment_item_ll_full.setVisibility(View.VISIBLE);
holder.comment_item_ll_full.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fullMap.put(commentEntity.getId(), true);
if (entity.getMore() == null) {
adapter.notifyItemChanged(index + 2);
essaydetails_rv_show.smoothScrollToPosition(index + 2);
} else {
adapter.notifyItemChanged(index + 2 + entity.getMore().size());
essaydetails_rv_show.smoothScrollToPosition(index + 2 + entity.getMore().size());
}
}
});
} else {
holder.comment_item_ll_full.setVisibility(View.GONE);
}
}
String date;
long time = System.currentTimeMillis()
- commentEntity.getTime() * 1000;
if (time <= 3600 * 1000) {
// 一小时内
int minute = (int) (time / 1000 / 60);
if (minute == 0) {
date = "刚刚";
} else {
date = minute + "分钟之前";
}
} else if (time <= 86400 * 1000) {
// 今天
int hour = (int) (time / 1000 / 3600);
if (hour == 0) {
hour = 1;
}
date = hour + "小时之前";
} else if (time <= 2 * 86400 * 1000) {
// 昨天
date = "昨天";
} else {
SimpleDateFormat format = new SimpleDateFormat("MM月dd日",
Locale.getDefault());
date = format.format(new Date(
commentEntity.getTime() * 1000));
}
if (entity.getMore() != null) {
holder.comment_item_tv_time.setText((position - 1 - entity.getMore().size()) + "\t\t\t\t" + date);
} else {
holder.comment_item_tv_time.setText((position - 1) + "\t\t\t\t" + date);
}
holder.comment_item_tv_like.setText(commentEntity.getFeedback().getUp() + "");
holder.comment_item_tv_unlike.setText(commentEntity.getFeedback().getDown() + "");
holder.comment_item_tv_like.setBackgroundResource(R.drawable.essay_comment_liked_style);
holder.comment_item_tv_unlike.setBackgroundResource(R.drawable.essay_comment_unliked_style);
ColorStateList colorStateList = getResources().getColorStateList(R.color.essay_text_style);
holder.comment_item_tv_like.setTextColor(colorStateList);
if (commentFeedbackMap != null) {
String action = commentFeedbackMap.get(commentEntity.getId());
if (action != null) {
if ("up".equals(action)) {
holder.comment_item_tv_like.setBackgroundResource(R.drawable.essay_comment_liked_dn);
holder.comment_item_tv_like.setTextColor(0xFFFFFFFF);
} else if ("down".equals(action)) {
holder.comment_item_tv_unlike.setBackgroundResource(R.drawable.essay_comment_unliked_dn);
}
}
}
holder.comment_item_tv_like.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Message msg = Message.obtain();
msg.what = Constants.SEND_COMMENT_FEEDBACK;
if (commentFeedbackMap != null) {
String key = commentEntity.getId();
String action = commentFeedbackMap.get(key);
if (action != null) {
if ("up".equals(action)) {
commentFeedbackMap.remove(key);
commentEntity.getFeedback().setUp(commentEntity.getFeedback().getUp() - 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(index + 2);
} else {
adapter.notifyItemChanged(index + 2 + entity.getMore().size());
}
msg.arg1 = 2;
msg.arg2 = index;
msg.obj = "CancelCommentLike=up";
timeMap.put("CancelCommentLike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
return;
} else {
commentEntity.getFeedback().setDown(commentEntity.getFeedback().getDown() - 1);
msg.obj = "SendCommentLike=down";
}
} else {
msg.obj = "SendCommentLike";
}
} else {
commentFeedbackMap = new ArrayMap<String, String>();
msg.obj = "SendCommentLike";
}
commentFeedbackMap.put(commentEntity.getId(), "up");
commentEntity.getFeedback().setUp(commentEntity.getFeedback().getUp() + 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(index + 2);
} else {
adapter.notifyItemChanged(index + 2 + entity.getMore().size());
}
msg.arg1 = 0;
msg.arg2 = index;
timeMap.put("SendCommentLike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
}
});
holder.comment_item_tv_unlike.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Message msg = Message.obtain();
msg.what = Constants.SEND_COMMENT_FEEDBACK;
if (commentFeedbackMap != null) {
String key = commentList.get(index).getId();
String action = commentFeedbackMap.get(key);
if (action != null) {
if ("down".equals(action)) {
commentFeedbackMap.remove(key);
commentList.get(index).getFeedback()
.setDown(commentList.get(index).getFeedback().getDown() - 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(index + 2);
} else {
adapter.notifyItemChanged(index + 2 + entity.getMore().size());
}
msg.arg1 = 2;
msg.arg2 = index;
msg.obj = "CancelCommentLike=down";
timeMap.put("CancelCommentLike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
return;
} else {
commentList.get(index).getFeedback().setUp(commentList.get(index).getFeedback().getUp() - 1);
msg.obj = "SendCommentUnlike=up";
}
} else {
msg.obj = "SendCommentUnlike";
}
} else {
commentFeedbackMap = new ArrayMap<String, String>();
msg.obj = "SendCommentUnlike";
}
commentFeedbackMap.put(commentList.get(index).getId(), "down");
commentList.get(index).getFeedback()
.setDown(commentList.get(index).getFeedback().getDown() + 1);
if (entity.getMore() == null) {
adapter.notifyItemChanged(index + 2);
} else {
adapter.notifyItemChanged(index + 2 + entity.getMore().size());
}
msg.arg1 = 1;
msg.arg2 = index;
timeMap.put("SendCommentUnlike", System.currentTimeMillis());
handler.sendMessageDelayed(msg, 1000);
}
});
} else if (isLoading
&& ((entity.getMore() == null && position == 2 + commentList
.size()) || (entity.getMore() != null && position == 2
+ entity.getMore().size() + commentList.size()))) {
if (isNetworkError) {
holder.footerview_progressbar.setVisibility(View.GONE);
holder.footerview_tv_loading.setText("加载失败,点击重试");
holder.rootView.setClickable(true);
holder.rootView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isNetworkError = false;
adapter.notifyItemChanged(adapter.getItemCount() - 1);
getComment(commentList.size());
}
});
} else {
holder.footerview_progressbar.setVisibility(View.VISIBLE);
holder.footerview_tv_loading.setText("加载中...");
holder.rootView.setClickable(false);
}
}
}
@Override
public int getItemCount() {
if (entity == null || entity.getAuthor() == null) {
return 0;
}
int commentSize = commentList.size();
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
if (isLoading) {
return 4 + moreSize + commentSize;
} else {
return 3 + moreSize + commentSize;
}
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
} else if (entity.getMore() != null && position >= 1 && position < 1 + entity.getMore().size()) {
return 1;
} else if ((entity.getMore() == null && position == 1)
|| (entity.getMore() != null && position == 1 + entity.getMore().size())) {
return 2;
} else if ((entity.getMore() == null && !commentList.isEmpty()
&& position >= 2 && position < 2 + commentList.size())
|| (entity.getMore() != null && !commentList.isEmpty()
&& position >= 2 + entity.getMore().size()
&& position < 2 + entity.getMore().size() + commentList.size())) {
return 3;
} else if (isLoading
&& ((entity.getMore() == null && position == 2 + commentList.size())
|| (entity.getMore() != null && position == 2 + entity.getMore().size() + commentList.size()))) {
return 4;
} else {
return 5;
}
}
}
public void onEventMainThread(EBPackage busFour) {
if (gameEntity != null && gameEntity.getApk().size() == 1) {
String packageName = gameEntity.getApk().get(0).getPackageName();
if (packageName.equals(busFour.getPackageName())) {
if ("安装".equals(busFour.getType())) {
essaydetails_tv_download.setVisibility(View.VISIBLE);
essaydetails_progressbar.setVisibility(View.GONE);
essaydetails_tv_per.setVisibility(View.GONE);
essaydetails_tv_download.setText("启动《"
+ gameEntity.getName() + "");
} else if ("卸载".equals(busFour.getType())) {
essaydetails_tv_download.setVisibility(View.VISIBLE);
essaydetails_progressbar.setVisibility(View.GONE);
essaydetails_tv_per.setVisibility(View.GONE);
essaydetails_tv_download.setText("下载《"
+ gameEntity.getName() + "");
}
}
}
}
public void onEventMainThread(EBNetworkState busNetworkState) {
if (busNetworkState.isNetworkConnected()) {
if (reuse_no_connection.getVisibility() == View.VISIBLE) {
essaydetails_rv_show.setVisibility(View.VISIBLE);
essaydetails_ll_loading.setVisibility(View.VISIBLE);
essaydetails_ll_bottom.setVisibility(View.VISIBLE);
reuse_no_connection.setVisibility(View.GONE);
handler.postDelayed(runnable, 1000);
} else if (isNetworkError) {
isNetworkError = false;
adapter.notifyItemChanged(adapter.getItemCount() - 1);
getComment(commentList.size());
}
}
}
public void onEventMainThread(EBPWDismiss dismiss) {
if (dismissEntity != null) {
dismissEntity.setShow(false);
}
}
private void invalidate() {
essaydetails_progressbar
.setProgress((int) (downloadEntry.getPercent() * 10));
switch (downloadEntry.getStatus()) {
case downloading:
essaydetails_tv_per.setText(downloadEntry.getPercent() + "%");
break;
case pause:
case neterror:
essaydetails_tv_per.setText("继续");
break;
case done:
EventBus.getDefault().post(
new EBPutUrl(gameEntity.getApk().get(0).getPackageName(),
downloadEntry.getUrl()));
essaydetails_tv_per.setText("安装");
break;
case cancel:
case hijack:
essaydetails_tv_download.setVisibility(View.VISIBLE);
essaydetails_progressbar.setVisibility(View.GONE);
essaydetails_tv_per.setVisibility(View.GONE);
if (TextUtils.isEmpty(gameEntity.getDownloadAddWord())) {
essaydetails_tv_download.setText("下载《" + gameEntity.getName() + "");
} else {
essaydetails_tv_download.setText("下载《" + gameEntity.getName() + "" + gameEntity.getDownloadAddWord());
}
break;
default:
break;
}
}
// 获取文章评论
private void getComment(int offset) {
JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
TimestampUtils.addTimestamp(
"http://comment.ghzhushou.com/v1d45/news/" + entity.getId() + "/comment?limit=10&offset=" + offset,
Constants.COMMENT_CD),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Utils.log(response.toString());
if (!isDestroy) {
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<CommentEntity>>() {}.getType();
ArrayList<CommentEntity> list = gson.fromJson(response.toString(), listType);
for (int i = 0, size = list.size() ; i < size ; i++){
commentList.add(list.get(i));
adapter.notifyItemInserted(adapter.getItemCount() - 2);
}
if (list.size() > 4){
essaydetails_rv_show.smoothScrollToPosition(adapter.getItemCount() - list.size() + 2);
} else {
essaydetails_rv_show.smoothScrollToPosition(adapter.getItemCount() - 1);
}
if (list.size() < 10) {
isLoading = false;
adapter.notifyItemRemoved(adapter.getItemCount() - 1);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 无网络连接和访问超时
if (error.getClass().equals(NoConnectionError.class)
|| error.getClass().equals(TimeoutError.class)) {
if (!isDestroy) {
// TODO 处理加载时断网或超时情况
toast("网络错误");
isNetworkError = true;
adapter.notifyItemChanged(adapter.getItemCount() - 2);
}
}
}
});
AppController.addToRequestQueue(request, NewsActivity.class);
}
private void showCommentDialog(final View v, CharSequence text,
int lineCount) {
KeyboardLayout contentView = (KeyboardLayout) View.inflate(this,
R.layout.dialog_essay_comment, null);
popupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, true);
final EditText content = (EditText) contentView
.findViewById(R.id.dialog_et_comment_content);
final TextView send = (TextView) contentView
.findViewById(R.id.dialog_tv_comment_send);
contentView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
essaydetails_tv_comment_content.setText(content.getText());
}
});
contentView
.setOnKeyboardChangedListener(new OnKeyboardChangedListener() {
@Override
public void OnKeyboardChanged(int w, int h, int oldw,
int oldh) {
if (oldh != 0 && h > oldh) {
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
essaydetails_tv_comment_content.setText(content
.getText());
}
}
}
});
content.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int line = content.getLineCount();
if (line != 0) {
LinearLayout.LayoutParams lparams = (LinearLayout.LayoutParams) content
.getLayoutParams();
if (line == 1) {
lparams.height = DisplayUtils.dip2px(
getApplicationContext(), 34);
} else {
lparams.height = DisplayUtils.dip2px(
getApplicationContext(), 20)
+ (line > 3 ? 3 : line)
* DisplayUtils.dip2px(getApplicationContext(),
12);
}
content.setLayoutParams(lparams);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
content.setText(text);
if (lineCount != 0) {
LinearLayout.LayoutParams lparams = (LinearLayout.LayoutParams) content
.getLayoutParams();
if (lineCount == 1) {
lparams.height = DisplayUtils.dip2px(getApplicationContext(),
34);
} else {
lparams.height = DisplayUtils.dip2px(getApplicationContext(),
20)
+ (lineCount > 3 ? 3 : lineCount)
* DisplayUtils.dip2px(getApplicationContext(), 12);
}
content.setLayoutParams(lparams);
}
content.requestFocus();
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
essaydetails_tv_comment_content.setText(content.getText());
sendComment(content.getText());
}
});
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getTintManager().setStatusBarTintResource(
R.color.theme_colors);
}
}
});
popupWindow.setFocusable(true);
popupWindow
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
// #0E6295 #0E6195
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getTintManager().setStatusBarTintColor(0xff0E6295);
}
}
// 发送评论
private void sendComment(final CharSequence text) {
if (text.length() == 0) {
toast("请输入评论内容!");
return;
}
final Dialog dialog = DialogUtils.showWaitDialog(this, "发送中...");
new Thread() {
@Override
public void run() {
String url = "http://comment.ghzhushou.com/v1d45/news/" + entity.getId()
+ "/comment?time=" + System.currentTimeMillis();
Utils.log("url = " + url);
Map<String, String> params = new HashMap<String, String>();
params.put("content", text.toString());
JSONObject body = new JSONObject(params);
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Method.POST, url, body.toString(),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log(response.toString());
dialog.dismiss();
try {
if (response.getString("status").equals("success")) {
essaydetails_tv_comment_content.setText("");
toast("发送成功");
Gson gson = new Gson();
CommentEntity commentEntity = gson.fromJson(response.getJSONObject("comment").toString(), CommentEntity.class);
commentList.add(0, commentEntity);
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
adapter.notifyItemInserted(2 + moreSize);
if (commentList.size() == 1) {
essaydetails_rv_show.smoothScrollToPosition(adapter.getItemCount() - 1);
} else {
essaydetails_rv_show.smoothScrollToPosition(1 + moreSize);
}
modifyNewsCommentVolleyCache(0, response.getJSONObject("comment"));
} else if (response.getString("status").equals("refuse")) {
toast("评论太频繁,请稍后再试");
} else if (response.getString("status").equals("device_block")
|| response.getString("status").equals("user_block")) {
toast("你已被禁言,请稍后再试");
} else {
toast("发送失败");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log(error.toString());
if (error.networkResponse != null) {
Utils.log(new String(
error.networkResponse.data));
}
dialog.dismiss();
toast("发送失败");
}
});
String token = TokenUtils.getToken(NewsActivity.this);
request.addHeader("Auth", token);
request.addHeader("Device",
DeviceUtils.getDeviceHeader(NewsActivity.this));
request.setShouldCache(false);
AppController.addToRequestQueue(request, NewsActivity.class);
}
}.start();
}
/*
* 修改新闻评论的volley缓存
*/
private void modifyNewsCommentVolleyCache(int offset, JSONObject commentData) {
File cacheDir = new File(getCacheDir(), DEFAULT_CACHE_DIR);
DiskBasedCache cache = new DiskBasedCache(cacheDir);
String key = TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/comment?limit=10&offset=" + offset, Constants.COMMENT_CD);
byte[] data = cache.getData(key);
if (data != null) {
try {
JSONArray jsonArray = new JSONArray(new String(GzipUtils.decompressBytes(data)));
JSONArray newComment = new JSONArray();
newComment.put(commentData);
for (int i = 0, size = jsonArray.length() > 9 ? 9 : jsonArray.length(); i < size; i++) {
newComment.put(jsonArray.get(i));
}
Utils.log(newComment.toString());
cache.modify(key, GzipUtils.compressBytes(newComment.toString().getBytes()));
if (jsonArray.length() == 10) {
modifyNewsCommentVolleyCache(offset + 10, jsonArray.getJSONObject(9));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Utils.log("modifyNewsCommentVolleyCache is null");
}
}
/*
* 修改新闻反馈的volley缓存
*/
private void modifyNewsFeedbackVolleyCache(String action, int value) {
if (TextUtils.isEmpty(action)) {
return;
}
String key = TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/feedback", Constants.COMMENT_CD);
File cacheDir = new File(getCacheDir(), DEFAULT_CACHE_DIR);
DiskBasedCache cache = new DiskBasedCache(cacheDir);
byte[] data = cache.getData(key);
if (data != null) {
try {
JSONObject jsonObject = new JSONObject(new String(GzipUtils.decompressBytes(data)));
jsonObject.put(action, jsonObject.getInt(action) + value);
Utils.log(jsonObject.toString());
cache.modify(key, GzipUtils.compressBytes(jsonObject.toString().getBytes()));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Utils.log("modifyNewsFeedbackVolleyCache is null");
}
}
/*
* 修改用户对新闻的反馈的volley缓存
*/
private void modifyUserNewsFeedbackVolleyCache(String action) {
String key = TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/user/feedback", Constants.COMMENT_CD);
File cacheDir = new File(getCacheDir(), DEFAULT_CACHE_DIR);
DiskBasedCache cache = new DiskBasedCache(cacheDir);
byte[] data = cache.getData(key);
if (data != null) {
try {
JSONObject jsonObject = new JSONObject(new String(GzipUtils.decompressBytes(data)));
if (!jsonObject.isNull("news")) {
if (action == null) {
modifyNewsFeedbackVolleyCache(jsonObject.getJSONObject("news").getString("action"), -1);
jsonObject.getJSONObject("news").put("action", "");
} else {
modifyNewsFeedbackVolleyCache(jsonObject.getJSONObject("news").getString("action"), -1);
jsonObject.getJSONObject("news").put("action", action);
modifyNewsFeedbackVolleyCache(jsonObject.getJSONObject("news").getString("action"), 1);
}
} else {
if (action != null) {
JSONObject news = new JSONObject();
news.put("action", action);
jsonObject.put("news", news);
modifyNewsFeedbackVolleyCache(action, 1);
}
}
Utils.log(jsonObject.toString());
cache.modify(key, GzipUtils.compressBytes(jsonObject.toString().getBytes()));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Utils.log("modifyUserNewsFeedbackVolleyCache is null");
}
}
/*
* 修改用户对评论的反馈的volley缓存
*/
private void modifyUserCommentFeedbackVolleyCache(String id, String action) {
String key = TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/user/feedback", Constants.COMMENT_CD);
File cacheDir = new File(getCacheDir(), DEFAULT_CACHE_DIR);
DiskBasedCache cache = new DiskBasedCache(cacheDir);
byte[] data = cache.getData(key);
if (data != null) {
try {
JSONObject jsonObject = new JSONObject(new String(GzipUtils.decompressBytes(data)));
JSONArray comment = jsonObject.getJSONArray("comment");
if (comment.length() != 0) {
if (action == null) {
JSONArray newComment = new JSONArray();
for (int i = 0; i < comment.length(); i++) {
JSONObject item = comment.getJSONObject(i);
if (!item.getString("id").equals(id)) {
newComment.put(item);
} else {
modifyCommentFeedbackVolleyCache(0, id, item.getString("action"), -1);
}
}
jsonObject.put("comment", newComment);
} else {
for (int i = 0; i < comment.length(); i++) {
JSONObject item = comment.getJSONObject(i);
if (item.getString("id").equals(id)) {
modifyCommentFeedbackVolleyCache(0, id, item.getString("action"), -1);
item.put("action", action);
modifyCommentFeedbackVolleyCache(0, id, item.getString("action"), 1);
break;
}
}
jsonObject.put("comment", comment);
}
} else {
if (action != null) {
JSONObject item = new JSONObject();
item.put("id", id);
item.put("action", action);
comment.put(item);
jsonObject.put("comment", comment);
modifyCommentFeedbackVolleyCache(0, id, action, 1);
}
}
Utils.log(jsonObject.toString());
cache.modify(key, GzipUtils.compressBytes(jsonObject.toString().getBytes()));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Utils.log("modifyUserCommentFeedbackVolleyCache is null");
}
}
/*
* 修改评论反馈的volley缓存
*/
private void modifyCommentFeedbackVolleyCache(int offset, String id, String action, int value) {
String key = TimestampUtils.addTimestamp("http://comment.ghzhushou.com/v1d45/news/"
+ entity.getId() + "/comment?limit=10&offset=" + offset, Constants.COMMENT_CD);
File cacheDir = new File(getCacheDir(), DEFAULT_CACHE_DIR);
DiskBasedCache cache = new DiskBasedCache(cacheDir);
byte[] data = cache.getData(key);
if (data != null) {
try {
JSONArray jsonArray = new JSONArray(new String(GzipUtils.decompressBytes(data)));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject comment = jsonArray.getJSONObject(i);
if (comment.getString("_id").equals(id)) {
JSONObject feedback = comment.getJSONObject("feedback");
feedback.put(action, feedback.getLong(action) + value);
feedback.put("val", feedback.getLong("up") - feedback.getLong("down"));
Utils.log(jsonArray.toString());
cache.modify(key, GzipUtils.compressBytes(jsonArray.toString().getBytes()));
return;
}
}
if (jsonArray.length() == 10) {
modifyCommentFeedbackVolleyCache(offset + 10, id, action, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Utils.log("modifyCommentFeedbackVolleyCache is null");
}
}
/*
* 修改新闻的反馈
*/
private void modifyNewsFeedback(String news_id, final String newAction, final int oldAction) {
final String url = "http://comment.ghzhushou.com/v1d45/news/" + news_id + "/feedback/" + newAction;
new Thread() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Method.POST, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log("modifyNewsFeedback = " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log("modifyNewsFeedback = " + error.toString());
if (error.networkResponse != null) {
Utils.log("modifyNewsFeedback = " + new String(error.networkResponse.data));
}
//TODO 失败回滚
String action = null;
if ("up".equals(newAction)) {
if (oldAction == 2) {
action = "down";
entity.setUp(entity.getUp() - 1);
entity.setDown(entity.getDown() + 1);
} else if (oldAction == 0) {
entity.setUp(entity.getUp() - 1);
} else {
action = "up";
}
} else if ("down".equals(newAction)) {
if (oldAction == 1) {
action = "up";
entity.setUp(entity.getUp() + 1);
entity.setDown(entity.getDown() - 1);
} else if (oldAction == 0) {
entity.setDown(entity.getDown() - 1);
} else {
action = "down";
}
}
modifyUserNewsFeedbackVolleyCache(action);
entity.setAction(action);
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
adapter.notifyItemChanged(1 + moreSize);
}
});
String token = TokenUtils.getToken(NewsActivity.this);
request.addHeader("Auth", token);
request.setShouldCache(false);
AppController.addToRequestQueue(request, NewsActivity.this);
}
}.start();
}
/*
* 取消对新闻的反馈
*/
private void cancelNewsFeedback(String news_id, final int oldAction) {
final String url = "http://comment.ghzhushou.com/v1d45/news/" + news_id + "/feedback";
new Thread() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Method.POST, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log("cancelNewsFeedback = " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log("cancelNewsFeedback = " + error.toString());
//TODO 失败回滚
if (oldAction == 1) {
entity.setAction("up");
entity.setUp(entity.getUp() + 1);
modifyUserNewsFeedbackVolleyCache("up");
} else if (oldAction == 2) {
entity.setAction("down");
entity.setDown(entity.getDown() + 1);
modifyUserNewsFeedbackVolleyCache("down");
}
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
adapter.notifyItemChanged(1 + moreSize);
}
});
String token = TokenUtils.getToken(NewsActivity.this);
request.addHeader("Auth", token);
request.setShouldCache(false);
AppController.addToRequestQueue(request, NewsActivity.this);
}
}.start();
}
/*
* 修改评论的反馈
*/
private void modifyCommentFeedback(String news_id, String comment_id, final String newAction, final String oldAction, final int index) {
final String url = "http://comment.ghzhushou.com/v1d45/news/" + news_id + "/comment/" + comment_id + "/feedback/" + newAction;
new Thread() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Method.POST, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log("modifyCommentFeedback = " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log("modifyCommentFeedback = " + error.toString());
if (error.networkResponse != null) {
Utils.log("modifyCommentFeedback = " + new String(error.networkResponse.data));
}
//TODO 失败回滚
String action = null;
if ("up".equals(newAction)) {
if ("down".equals(oldAction)) {
commentList.get(index).getFeedback().setUp(commentList.get(index).getFeedback().getUp() - 1);
commentList.get(index).getFeedback().setDown(commentList.get(index).getFeedback().getDown() + 1);
commentFeedbackMap.put(commentList.get(index).getId(), "down");
action = "down";
} else if (oldAction == null) {
commentList.get(index).getFeedback().setUp(commentList.get(index).getFeedback().getUp() - 1);
commentFeedbackMap.remove(commentList.get(index).getId());
} else {
action = "up";
}
} else if ("down".equals(newAction)) {
if ("up".equals(oldAction)) {
commentList.get(index).getFeedback().setUp(commentList.get(index).getFeedback().getUp() + 1);
commentList.get(index).getFeedback().setDown(commentList.get(index).getFeedback().getDown() - 1);
commentFeedbackMap.put(commentList.get(index).getId(), "up");
action = "up";
} else if (oldAction == null) {
commentList.get(index).getFeedback().setDown(commentList.get(index).getFeedback().getDown() - 1);
commentFeedbackMap.remove(commentList.get(index).getId());
} else {
action = "down";
}
}
modifyUserCommentFeedbackVolleyCache(commentList.get(index).getId(), action);
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
adapter.notifyItemChanged(index + 2 + moreSize);
}
});
String token = TokenUtils.getToken(NewsActivity.this);
request.addHeader("Auth", token);
request.setShouldCache(false);
AppController.addToRequestQueue(request, NewsActivity.this);
}
}.start();
}
/*
* 取消对评论的反馈
*/
private void cancelCommentFeedback(String news_id, String comment_id, final String oldAction, final int index) {
final String url = "http://comment.ghzhushou.com/v1d45/news/" + news_id + "/comment/"
+ comment_id + "/feedback";
new Thread() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Method.POST, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Utils.log("cancelCommentFeedback = " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Utils.log("cancelCommentFeedback = " + error.toString());
if (error.networkResponse != null) {
Utils.log("cancelCommentFeedback = " + new String(error.networkResponse.data));
}
//TODO 失败回滚
if ("up".equals(oldAction)) {
commentList.get(index).getFeedback().setUp(commentList.get(index).getFeedback().getUp() + 1);
commentFeedbackMap.put(commentList.get(index).getId(), "up");
modifyUserCommentFeedbackVolleyCache(commentList.get(index).getId(), "up");
} else if ("down".equals(oldAction)) {
commentList.get(index).getFeedback().setDown(commentList.get(index).getFeedback().getDown() + 1);
commentFeedbackMap.put(commentList.get(index).getId(), "down");
modifyUserCommentFeedbackVolleyCache(commentList.get(index).getId(), "down");
}
int moreSize = entity.getMore() == null ? 0 : entity.getMore().size();
adapter.notifyItemChanged(index + 2 + moreSize);
}
});
String token = TokenUtils.getToken(NewsActivity.this);
request.addHeader("Auth", token);
request.setShouldCache(false);
AppController.addToRequestQueue(request, NewsActivity.this);
}
}.start();
}
@Override
public void onResume() {
super.onResume();
if (gameEntity != null && gameEntity.getApk().size() == 1) {
if (PackageManager.isInstalled(gameEntity.getApk().get(0).getPackageName())) {
essaydetails_tv_download.setVisibility(View.VISIBLE);
essaydetails_progressbar.setVisibility(View.GONE);
essaydetails_tv_per.setVisibility(View.GONE);
if (TextUtils.isEmpty(gameEntity.getDownloadAddWord())) {
essaydetails_tv_download.setText("启动《" + gameEntity.getName() + "");
} else {
essaydetails_tv_download.setText("启动《" + gameEntity.getName() + "" + gameEntity.getDownloadAddWord());
}
} else {
String url = gameEntity.getApk().get(0).getUrl();
for (DownloadEntry entry : DownloadManager.getInstance(getApplicationContext()).getAll()) {
if (url.equals(entry.getUrl())) {
downloadEntry = entry;
essaydetails_tv_download.setVisibility(View.GONE);
essaydetails_progressbar.setVisibility(View.VISIBLE);
essaydetails_tv_per.setVisibility(View.VISIBLE);
invalidate();
break;
}
}
}
}
DownloadManager.getInstance(this).addObserver(dataWatcher);
}
@Override
public void finish() {
long end = Calendar.getInstance().getTimeInMillis();
int seconds = (int) ((end - start) / 1000);
String cost = "";
if (seconds < 5) {
cost = "小于5秒";
} else if (seconds < 30) {
cost = "5秒30秒";
} else if (seconds < 60) {
cost = "30秒60秒";
} else {
cost = "大于60秒";
}
// 阅读报告
Map<String, Object> kv = new HashMap<String, Object>();
kv.put(entrance, "阅读数");
kv.put(entrance, "用时:" + cost);
TCAgent.onEvent(NewsActivity.this, "文章数据", entity.getTitle(), kv);
if ("主页-卡牌头条".equals(entrance)) {
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put(entity.getTitle(), "阅读数");
kv2.put(entity.getTitle(), "用时:" + cost);
TCAgent.onEvent(this, "主页数据", "卡牌头条", kv2);
} else if ("主页-卡牌攻略".equals(entrance)) {
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put(entity.getTitle(), "阅读数");
kv2.put(entity.getTitle(), "用时:" + cost);
TCAgent.onEvent(this, "主页数据", "卡牌攻略", kv2);
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", entity.getTitle());
map.put("type", entity.getType());
map.put("author", entity.getAuthor());
if (gameEntity != null) {
map.put("game", gameEntity.getName());
}
map.put("time", seconds);
map.put("createdOn", System.currentTimeMillis() / 1000);
map.put("from", entrance);
DataCollectionManager.onEvent(this, "news", map);
super.finish();
}
@Override
protected void onPause() {
super.onPause();
statusMap.clear();
DownloadManager.getInstance(this).removeObserver(dataWatcher);
if (!isSentReport) {
long end = Calendar.getInstance().getTimeInMillis();
int seconds = (int) ((end - start) / 1000);
String cost;
if (seconds < 5) {
cost = "小于5秒";
} else if (seconds < 30) {
cost = "5秒30秒";
} else if (seconds < 60) {
cost = "30秒60秒";
} else {
cost = "大于60秒";
}
// 阅读报告
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("用时", cost);
TCAgent.onEvent(NewsActivity.this, "阅读文章", entity.getTitle(), kv);
isSentReport = true;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
isDestroy = true;
AppController.canclePendingRequests(NewsActivity.class);
essaydetails_ll_loading = null;
essaydetails_ll_bottom = null;
reuse_no_connection = null;
essaydetails_ll_comment = null;
entity = null;
actionbar_tv_title = null;
essaydetails_tv_download = null;
essaydetails_tv_per = null;
essaydetails_tv_comment_content = null;
essaydetails_tv_comment_send = null;
essaydetails_iv_share = null;
essaydetails_progressbar = null;
gameEntity = null;
downloadEntry = null;
essaydetails_rv_show = null;
adapter = null;
linearLayoutManager = null;
entrance = null;
dismissEntity = null;
lastTimeMap = null;
statusMap = null;
timeMap = null;
commentList = null;
commentFeedbackMap = null;
popupWindow = null;
handler = null;
dataWatcher = null;
}
}