ShareActivity.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. package com.ouling.weibo;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.File;
  4. import java.io.ObjectInputStream;
  5. import java.net.URLEncoder;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import org.apache.commons.codec.binary.Base64;
  9. import android.app.Activity;
  10. import android.app.AlertDialog;
  11. import android.app.ProgressDialog;
  12. import android.content.ContentResolver;
  13. import android.content.Context;
  14. import android.content.DialogInterface;
  15. import android.content.Intent;
  16. import android.content.SharedPreferences;
  17. import android.database.Cursor;
  18. import android.graphics.Bitmap;
  19. import android.graphics.BitmapFactory;
  20. import android.graphics.Color;
  21. import android.graphics.drawable.BitmapDrawable;
  22. import android.net.Uri;
  23. import android.os.Bundle;
  24. import android.os.Handler;
  25. import android.os.Message;
  26. import android.provider.MediaStore;
  27. import android.text.Editable;
  28. import android.text.TextUtils;
  29. import android.text.TextWatcher;
  30. import android.util.Log;
  31. import android.view.KeyEvent;
  32. import android.view.View;
  33. import android.view.View.OnClickListener;
  34. import android.view.ViewGroup;
  35. import android.view.Window;
  36. import android.view.inputmethod.InputMethodManager;
  37. import android.widget.AdapterView;
  38. import android.widget.AdapterView.OnItemClickListener;
  39. import android.widget.BaseAdapter;
  40. import android.widget.Button;
  41. import android.widget.EditText;
  42. import android.widget.GridView;
  43. import android.widget.ImageButton;
  44. import android.widget.ImageView;
  45. import android.widget.TextView;
  46. import android.widget.Toast;
  47. import com.ouling.weibo.OAuth.OAuthConstant;
  48. import com.ouling.weibo.basic.Weibo;
  49. import com.ouling.weibo.http.AccessToken;
  50. import com.ouling.weibo.util.ImageRel;
  51. import com.ouling.weibo.util.InfoHelper;
  52. import com.ouling.weibo.util.HighLightTextView;
  53. /**
  54. * 发表微博
  55. *
  56. *
  57. */
  58. public class ShareActivity extends Activity {
  59. private static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
  60. private static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
  61. private static final int UPDATE_SUCCESS = 0;
  62. private static final int UPDATE_FAILED = 1;
  63. private Button btn_share;
  64. // private Button btn_emtions;
  65. private ImageButton imgChooseBtn;
  66. private ImageView imageView;
  67. private TextView wordCounterTextView;
  68. private EditText contentEditText;
  69. private ProgressDialog progressDialog;
  70. private GridView gridView;
  71. private GridAdapter adapter;
  72. private String uploadImage = null;
  73. private List<Bitmap> emotioms = new ArrayList<Bitmap>();
  74. private List<String> emotioms_name = new ArrayList<String>();
  75. private boolean isInputMethodShow;
  76. private boolean isGridViewShow;
  77. private String lastString;
  78. private Handler handler = new Handler() {
  79. @Override
  80. public void handleMessage(Message msg) {
  81. super.handleMessage(msg);
  82. switch (msg.what) {
  83. case UPDATE_SUCCESS:
  84. Toast.makeText(ShareActivity.this, "发微博成功",
  85. Toast.LENGTH_LONG).show();
  86. progressDialog.dismiss();
  87. ShareActivity.this.finish();
  88. break;
  89. case UPDATE_FAILED:
  90. Toast.makeText(ShareActivity.this, "发微博失败",
  91. Toast.LENGTH_LONG).show();
  92. progressDialog.dismiss();
  93. break;
  94. }
  95. }
  96. };
  97. private Runnable updateWeibo = new Runnable() {
  98. public void run() {
  99. try {
  100. Weibo weibo = OAuthConstant.getInstance().getWeibo();
  101. if (weibo == null) {
  102. SharedPreferences sp = getSharedPreferences("ouling",
  103. Context.MODE_PRIVATE);
  104. String s = sp.getString("accessToken", null);
  105. if (s != null) {
  106. byte[] bytes = Base64.decodeBase64(s.getBytes());
  107. ByteArrayInputStream bais = new ByteArrayInputStream(
  108. bytes);
  109. ObjectInputStream ois = new ObjectInputStream(bais);
  110. AccessToken accessToken = (AccessToken) ois
  111. .readObject();
  112. if (accessToken != null)
  113. OAuthConstant.getInstance().setAccessToken(
  114. accessToken);
  115. }
  116. }
  117. String msg = contentEditText.getText().toString();
  118. if (msg.getBytes().length != msg.length()) {
  119. msg = URLEncoder.encode(msg, "UTF-8");
  120. }
  121. if (TextUtils.isEmpty(uploadImage)) {
  122. weibo.updateStatus(msg);
  123. } else {
  124. File file = new File(uploadImage);
  125. weibo.uploadStatus(msg, file);
  126. }
  127. handler.sendEmptyMessage(UPDATE_SUCCESS);
  128. } catch (Exception e) {
  129. e.printStackTrace();
  130. handler.sendEmptyMessage(UPDATE_FAILED);
  131. }
  132. }
  133. };
  134. @Override
  135. public void onCreate(Bundle savedInstanceState) {
  136. super.onCreate(savedInstanceState);
  137. requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
  138. setContentView(R.layout.sharemain);
  139. // getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
  140. // R.layout.shareheader);
  141. System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
  142. System.setProperty("weibo4j.oauth.consumerSecret",
  143. Weibo.CONSUMER_SECRET);
  144. isInputMethodShow = isGridViewShow = false;
  145. lastString = "";
  146. getEmotions();
  147. gridView = (GridView) findViewById(R.id.gridView);
  148. // btn_share = (Button) findViewById(R.id.btn_share);
  149. // btn_emtions = (Button) findViewById(R.id.btn_add_emotion);
  150. btn_share=(Button)findViewById(R.id.btn_add_emotion);
  151. btn_share.setText("分享");
  152. imgChooseBtn = (ImageButton) findViewById(R.id.share_imagechoose);
  153. imageView = (ImageView) findViewById(R.id.share_image);
  154. wordCounterTextView = (TextView) findViewById(R.id.share_word_counter);
  155. contentEditText = (EditText) findViewById(R.id.share_content);
  156. Intent it = getIntent();
  157. if (it != null && it.getAction() != null
  158. && it.getAction().equals(Intent.ACTION_SEND)) {
  159. Bundle extras = it.getExtras();
  160. if (extras.containsKey("android.intent.extra.STREAM")) {
  161. Uri thisUri = (Uri) extras.get("android.intent.extra.STREAM");
  162. String thePath = InfoHelper
  163. .getAbsolutePathFromNoStandardUri(thisUri);
  164. if (TextUtils.isEmpty(thePath)) {
  165. uploadImage = getAbsoluteImagePath(thisUri);
  166. } else {
  167. uploadImage = thePath;
  168. }
  169. contentEditText.setText("分享图片");
  170. wordCounterTextView.setText(String.valueOf(140 - "分享图片"
  171. .length()));
  172. }
  173. }
  174. adapter = new GridAdapter();
  175. gridView.setAdapter(adapter);
  176. gridView.setVisibility(View.GONE);
  177. adapter.notifyDataSetChanged();
  178. gridView.setOnItemClickListener(new OnItemClickListener() {
  179. @Override
  180. public void onItemClick(AdapterView<?> parent, View view,
  181. int position, long id) {
  182. String text = contentEditText.getText().toString();
  183. if (TextUtils.isEmpty(text))
  184. text = "";
  185. text = text + emotioms_name.get(position);
  186. contentEditText.setText(text);
  187. }
  188. });
  189. btn_share.setOnClickListener(new OnClickListener() {
  190. @Override
  191. public void onClick(View v) {
  192. if (InfoHelper.checkNetWork(ShareActivity.this) && isChecked()) {
  193. progressDialog.show();
  194. new Thread(updateWeibo).start();
  195. }
  196. }
  197. });
  198. // btn_emtions.setOnClickListener(new OnClickListener() {
  199. //
  200. // @Override
  201. // public void onClick(View v) {
  202. // if (btn_emtions.getText().equals("输入文字")) {
  203. // btn_emtions.setText("添加表情");
  204. //
  205. // InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  206. // inputMethodManager.toggleSoftInput(0,
  207. // InputMethodManager.SHOW_FORCED);
  208. // gridView.setVisibility(View.GONE);
  209. //
  210. // isInputMethodShow = true;
  211. // isGridViewShow = false;
  212. //
  213. // } else {
  214. // btn_emtions.setText("输入文字");
  215. //
  216. // InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  217. // inputMethodManager.hideSoftInputFromWindow(
  218. // contentEditText.getApplicationWindowToken(), 0);
  219. // gridView.setVisibility(View.VISIBLE);
  220. //
  221. // isInputMethodShow = false;
  222. // isGridViewShow = true;
  223. // }
  224. // }
  225. // });
  226. imgChooseBtn.setOnClickListener(new OnClickListener() {
  227. @Override
  228. public void onClick(View v) {
  229. CharSequence[] items = { "手机相册", "手机拍照", "清除照片" };
  230. imageChooseItem(items);
  231. }
  232. });
  233. contentEditText.addTextChangedListener(new TextWatcher() {
  234. @Override
  235. public void onTextChanged(CharSequence s, int start, int before,
  236. int count) {
  237. if (lastString.equals(s.toString()))
  238. return;
  239. Log.d("onTextChanged", "s: " + s.toString());
  240. Log.d("onTextChanged", "lastString: " + lastString);
  241. lastString = new String(s.toString());
  242. textCountSet();
  243. }
  244. @Override
  245. public void beforeTextChanged(CharSequence s, int start, int count,
  246. int after) {
  247. }
  248. @Override
  249. public void afterTextChanged(Editable s) {
  250. }
  251. });
  252. contentEditText.setOnClickListener(new OnClickListener() {
  253. @Override
  254. public void onClick(View v) {
  255. // InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  256. // inputMethodManager.toggleSoftInput(0,
  257. // InputMethodManager.SHOW_FORCED);
  258. gridView.setVisibility(View.GONE);
  259. // btn_emtions.setText("添加表情");
  260. isInputMethodShow = true;
  261. isGridViewShow = false;
  262. }
  263. });
  264. if (!TextUtils.isEmpty(uploadImage)) {
  265. String imageName = uploadImage.substring(uploadImage
  266. .lastIndexOf(File.separator) + 1);
  267. Bitmap bitmap = loadImgThumbnail(imageName,
  268. MediaStore.Images.Thumbnails.MICRO_KIND);
  269. if (bitmap != null) {
  270. imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
  271. imageView.setOnClickListener(new OnClickListener() {
  272. @Override
  273. public void onClick(View v) {
  274. Intent intent = new Intent();
  275. intent.setAction(android.content.Intent.ACTION_VIEW);
  276. intent.setDataAndType(
  277. Uri.fromFile(new File(uploadImage)), "image/*");
  278. startActivity(intent);
  279. }
  280. });
  281. }
  282. }
  283. progressDialog = new ProgressDialog(ShareActivity.this);
  284. progressDialog.setMessage("分享中...");
  285. progressDialog.setIndeterminate(false);
  286. progressDialog.setCancelable(true);
  287. }
  288. @Override
  289. public boolean onKeyDown(int keyCode, KeyEvent event) {
  290. if (keyCode == KeyEvent.KEYCODE_BACK) {
  291. InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  292. inputMethodManager.hideSoftInputFromWindow(
  293. contentEditText.getApplicationWindowToken(), 0);
  294. gridView.setVisibility(View.GONE);
  295. if (isInputMethodShow || isGridViewShow) {
  296. isInputMethodShow = isGridViewShow = false;
  297. return true;
  298. }
  299. new AlertDialog.Builder(ShareActivity.this)
  300. .setMessage("确认要退出发微博吗?")
  301. .setPositiveButton("确定",
  302. new DialogInterface.OnClickListener() {
  303. @Override
  304. public void onClick(DialogInterface dialog,
  305. int which) {
  306. ShareActivity.this.finish();
  307. }
  308. })
  309. .setNegativeButton("取消",
  310. new DialogInterface.OnClickListener() {
  311. @Override
  312. public void onClick(DialogInterface dialog,
  313. int which) {
  314. }
  315. }).show();
  316. isInputMethodShow = isGridViewShow = false;
  317. return true;
  318. }
  319. return false;
  320. }
  321. private void getEmotions() {
  322. emotioms.clear();
  323. emotioms_name.clear();
  324. File file = new File(InfoHelper.getEmotionPath());
  325. File[] files = file.listFiles();
  326. Log.d(InfoHelper.TAG, "files size " + files.length);
  327. try {
  328. for (File tmp : files) {
  329. emotioms.add(BitmapFactory.decodeFile(tmp.getAbsolutePath()));
  330. emotioms_name.add(tmp.getName());
  331. }
  332. } catch (Exception e) {
  333. e.printStackTrace();
  334. }
  335. }
  336. @Override
  337. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  338. if (requestCode == REQUEST_CODE_GETIMAGE_BYSDCARD) {
  339. if (resultCode != RESULT_OK) {
  340. return;
  341. }
  342. if (data == null)
  343. return;
  344. Uri thisUri = data.getData();
  345. String thePath = InfoHelper
  346. .getAbsolutePathFromNoStandardUri(thisUri);
  347. // 如果是标准Uri
  348. if (TextUtils.isEmpty(thePath)) {
  349. uploadImage = getAbsoluteImagePath(thisUri);
  350. } else {
  351. uploadImage = thePath;
  352. }
  353. String imageName = uploadImage.substring(uploadImage
  354. .lastIndexOf(File.separator) + 1);
  355. Bitmap bitmap = loadImgThumbnail(imageName,
  356. MediaStore.Images.Thumbnails.MICRO_KIND);
  357. if (bitmap != null) {
  358. imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
  359. }
  360. }
  361. // 拍摄图片
  362. else if (requestCode == REQUEST_CODE_GETIMAGE_BYCAMERA) {
  363. if (resultCode != RESULT_OK) {
  364. return;
  365. }
  366. super.onActivityResult(requestCode, resultCode, data);
  367. Bitmap bitmap = InfoHelper.getScaleBitmap(ShareActivity.this,
  368. uploadImage);
  369. if (bitmap != null) {
  370. imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
  371. }
  372. }
  373. imageView.setOnClickListener(new OnClickListener() {
  374. @Override
  375. public void onClick(View v) {
  376. Intent intent = new Intent();
  377. intent.setAction(android.content.Intent.ACTION_VIEW);
  378. intent.setDataAndType(Uri.fromFile(new File(uploadImage)),
  379. "image/*");
  380. startActivity(intent);
  381. }
  382. });
  383. }
  384. /**
  385. * 获取图片缩略图 只有Android2.1以上版本支持
  386. *
  387. * @param imageName
  388. * @param kind
  389. * MediaStore.Images.Thumbnails.MICRO_KIND
  390. * @return
  391. */
  392. protected Bitmap loadImgThumbnail(String imageName, int kind) {
  393. Bitmap bitmap = null;
  394. String[] proj = { MediaStore.Images.Media._ID,
  395. MediaStore.Images.Media.DISPLAY_NAME };
  396. Cursor cursor = managedQuery(
  397. MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
  398. MediaStore.Images.Media.DISPLAY_NAME + "='" + imageName + "'",
  399. null, null);
  400. if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
  401. ContentResolver crThumb = getContentResolver();
  402. BitmapFactory.Options options = new BitmapFactory.Options();
  403. options.inSampleSize = 1;
  404. bitmap = MediaStore.Images.Thumbnails.getThumbnail(crThumb,
  405. cursor.getInt(0), kind, options);
  406. }
  407. return bitmap;
  408. }
  409. /**
  410. * 通过uri获取文件的绝对路径
  411. *
  412. * @param uri
  413. * @return
  414. */
  415. protected String getAbsoluteImagePath(Uri uri) {
  416. String imagePath = "";
  417. String[] proj = { MediaStore.Images.Media.DATA };
  418. Cursor cursor = managedQuery(uri, proj, null, null, null);
  419. if (cursor != null) {
  420. int column_index = cursor
  421. .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  422. if (cursor.getCount() > 0 && cursor.moveToFirst()) {
  423. imagePath = cursor.getString(column_index);
  424. }
  425. }
  426. return imagePath;
  427. }
  428. /**
  429. * 检查字数是否合法
  430. *
  431. * @return
  432. */
  433. private boolean isChecked() {
  434. if (TextUtils.isEmpty(contentEditText.getText().toString())) {
  435. Toast.makeText(ShareActivity.this, "说点什么吧", Toast.LENGTH_SHORT)
  436. .show();
  437. return false;
  438. } else if (contentEditText.getText().toString().length() > 140) {
  439. int currentLength = contentEditText.getText().toString().length();
  440. if (TextUtils.isEmpty(uploadImage)) {
  441. new AlertDialog.Builder(this)
  442. .setMessage("微博内容过长,是否已纸微博形式分享?")
  443. .setPositiveButton("确定",
  444. new DialogInterface.OnClickListener() {
  445. @Override
  446. public void onClick(DialogInterface dialog,
  447. int which) {
  448. progressDialog.show();
  449. Bitmap bitmap = ImageRel
  450. .createBitmapFromText(contentEditText
  451. .getText().toString());
  452. uploadImage = InfoHelper.getWeiboPath()
  453. + InfoHelper.getFileName();
  454. ImageRel.saveMyBitmap(uploadImage,
  455. bitmap);
  456. contentEditText.setText("#纸微博#");
  457. new Thread(updateWeibo).start();
  458. }
  459. })
  460. .setNegativeButton("返回",
  461. new DialogInterface.OnClickListener() {
  462. @Override
  463. public void onClick(DialogInterface dialog,
  464. int which) {
  465. }
  466. }).show();
  467. } else {
  468. Toast.makeText(ShareActivity.this,
  469. "已超出" + (currentLength - 140) + "字", Toast.LENGTH_SHORT)
  470. .show();
  471. }
  472. return false;
  473. }
  474. return true;
  475. }
  476. /**
  477. * 图片选择功能的选择
  478. *
  479. * @param items
  480. */
  481. public void imageChooseItem(CharSequence[] items) {
  482. new AlertDialog.Builder(ShareActivity.this).setTitle("增加图片")
  483. .setItems(items, new DialogInterface.OnClickListener() {
  484. public void onClick(DialogInterface dialog, int item) {
  485. // 手机选图
  486. if (item == 0) {
  487. Intent intent = new Intent(
  488. Intent.ACTION_GET_CONTENT);
  489. intent.setType("image/*");
  490. startActivityForResult(intent,
  491. REQUEST_CODE_GETIMAGE_BYSDCARD);
  492. }
  493. // 拍照
  494. else if (item == 1) {
  495. Intent intent = new Intent(
  496. "android.media.action.IMAGE_CAPTURE");
  497. String fileName = InfoHelper.getWeiboPath()
  498. + InfoHelper.getFileName() + ".jpg";
  499. intent.putExtra(MediaStore.EXTRA_OUTPUT,
  500. Uri.fromFile(new File(fileName)));
  501. startActivityForResult(intent,
  502. REQUEST_CODE_GETIMAGE_BYCAMERA);
  503. } else if (item == 2) {
  504. uploadImage = null;
  505. imageView.setBackgroundDrawable(null);
  506. }
  507. }
  508. }).show();
  509. }
  510. /**
  511. * 设置微博字数
  512. */
  513. private void textCountSet() {
  514. String textContent = contentEditText.getText().toString();
  515. if (TextUtils.isEmpty(textContent))
  516. textContent = "";
  517. int remainLength = 140 - textContent.length();
  518. if (remainLength >= 0) {
  519. wordCounterTextView.setTextColor(Color.BLACK);
  520. } else {
  521. wordCounterTextView.setTextColor(Color.RED);
  522. }
  523. HighLightTextView.setHighLightText(contentEditText, textContent);
  524. wordCounterTextView.setText(String.valueOf(remainLength));
  525. contentEditText.setSelection(contentEditText.length());
  526. }
  527. class GridAdapter extends BaseAdapter {
  528. @Override
  529. public int getCount() {
  530. return emotioms.size();
  531. }
  532. @Override
  533. public Bitmap getItem(int position) {
  534. return emotioms.get(position);
  535. }
  536. @Override
  537. public long getItemId(int position) {
  538. return position;
  539. }
  540. @Override
  541. public View getView(int position, View convertView, ViewGroup parent) {
  542. ImageView imageView;
  543. if (convertView == null) {
  544. imageView = new ImageView(ShareActivity.this);
  545. imageView.setLayoutParams(new GridView.LayoutParams(45, 45));
  546. imageView.setAdjustViewBounds(false);
  547. imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
  548. imageView.setPadding(8, 8, 8, 8);
  549. } else {
  550. imageView = (ImageView) convertView;
  551. }
  552. imageView.setImageBitmap(emotioms.get(position));
  553. return imageView;
  554. }
  555. }
  556. }