android 私有(private)聊天自动刷新

标签 android mysql google-cloud-messaging

我正在制作一个聊天应用程序,我希望私有(private)聊天能够快速,因为我正在使用自动刷新和异步任务。但是当我第一次去聊天类(class)但当我返回时它刷新得很快它再次变慢并且需要时间刷新...并且向数据库发送消息很慢。

如果我使用sqlite定期将数据保存在mysql数据库中。它会使其保存速度更快吗,因为我将从 sqlite 数据库中读取......并且仅将新数据从 mysql 加载到 sqlite

这是代码。

package com.mall.our;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mall.first.JSONParser;
import com.mall.first.MessageCategoryList;
import com.mall.first.R;
import com.mall.our.Chat.LoadComments;

import android.app.ListActivity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Chatting extends ListActivity {
// fr the sending of message
    private static final String TAG_POSTS = "posts";
    public static final String TAG_ID = "id";
    public static final String TAG_time = "time";
    public static final String TAG_state = "state";
    public static final String TAG_MESSAGE = "categories_message";
    public static final String TAG_CATEGORIES_LOGO = "categories_logo";
    public static final String TAG_from = "from ";
    //end


    JSONParser jsonParser = new JSONParser();
    private ProgressDialog pDialog;

    private static final String URL_CATEGORY = "http://www.thethinker.com.ng/ochat/selectmess.php";
    private static final String url = "http://www.thethinker.com.ng/ochat/sendmessage.php";
    private static final String ur = "http://www.thethinker.com.ng/ochat/seen.php";
    private BaseAdapter mAdapter;
    EditText mess;
    private ListView lv;
    ImageButton send;
    private static final String TAG_SUCCESS = "success";
    Intent b = getIntent();
    String state;
    int flag = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.yon);
        mess = (EditText) findViewById(R.id.mess);
        send = (ImageButton) findViewById(R.id.send);
        lv = getListView();
        lv.setDivider(null);
        ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

        /*This schedules a runnable task every second*/
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
          public void run() 
          {
            runOnUiThread(new Runnable(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    new LoadComments().execute();
                }

            });
          }
        }, 0, 5, TimeUnit.SECONDS);
                ff();
        sending();
    }




    private void sending() {
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {


                if (!isOnline(Chatting.this)) {
                    Toast.makeText(Chatting.this, "No network connection",
                            Toast.LENGTH_LONG).show();
                    return;
                }


                new sendtext().execute();

            }


            private boolean isOnline(Context mContext) {
                ConnectivityManager cm = (ConnectivityManager) mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                    return true;
                }
                return false;
            }

        });

    }
    public void ff(){
        Bundle go = getIntent().getExtras();

String friendname =  go.getString("po");
    TextView name = (TextView) findViewById(R.id.user);

    name.setText(friendname);

}

        class LoadComments extends
            AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
        private ProgressDialog pDialog;
        int priorPosition=  getListView().getFirstVisiblePosition();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Chatting.this);

            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);

        }

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                Void... arg0) {
               int successr;

            ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();

            SharedPreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(Chatting.this);
            Bundle go = getIntent().getExtras();

            String friend =  go.getString("po");
            String username = sp.getString("username", "anon");

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("friend", friend));
            JSONObject json = jsonParser.makeHttpRequest(URL_CATEGORY, "POST",
                    params);


            try {

                List<NameValuePair> seen = new ArrayList<NameValuePair>();
                seen.add(new BasicNameValuePair("username", username));
                seen.add(new BasicNameValuePair("friend", friend));

                successr = json.getInt(TAG_SUCCESS);
                JSONArray categories = json.getJSONArray(TAG_POSTS);

                for (int i = 0; i < categories.length(); i++) {
                    String id = categories.getJSONObject(i).getString("TAG_ID");
                    String time = categories.getJSONObject(i).getString(
                            "TAG_time");
                    String songs_count = categories.getJSONObject(i).getString(
                            "TAG_CATEGORIES_COUNT");
                    String from = categories.getJSONObject(i).getString(
                            "TAG_from");
                state = categories.getJSONObject(i).getString(
                            "TAG_state");

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_ID, id);
                    map.put(TAG_time, time);
                    map.put(TAG_MESSAGE, songs_count);
                    map.put(TAG_from, from);
                    map.put(TAG_state, state);


                    categoryList.add(map);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return categoryList;
        }

        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
            super.onPostExecute(result);


            mAdapter = new MessageCategoryList(Chatting.this,result);
            lv.setAdapter(mAdapter);
            getListView().setSelection(priorPosition);

            if(mAdapter == null)
            {
                 lv.setAdapter(mAdapter);
            }
            else
            {
                mAdapter.notifyDataSetChanged();
            }

        }
    }

    class sendtext extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Chatting.this);
            pDialog.setMessage("posting...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg0) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            SharedPreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(Chatting.this);
            String post_username = sp.getString("username", "anon");

            String friendname = sp.getString("value", "anon");
            String picc = sp.getString("pic", "anon");
            String message = mess.getText().toString();

            params.add(new BasicNameValuePair("from", post_username));
            params.add(new BasicNameValuePair("message", message));
            params.add(new BasicNameValuePair("to", friendname));
            params.add(new BasicNameValuePair("pic", picc));

            JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
            Log.d("Create Response", json.toString());
            try {
                int success = json.getInt(TAG_SUCCESS);

            } catch (JSONException e) {
                e.printStackTrace();
            }   
            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if (flag == 1)
                Toast.makeText(Chatting.this, " saved", Toast.LENGTH_LONG)
                        .show();
            mess.setText("");
        }


      }

}

我做了一些研究,发现了这个教程 http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/但教程是关于群聊的……无论如何,他们都要为私有(private)聊天创建套接字……

最佳答案

你需要管理内存。 减慢垃圾收集器的频率以增加垃圾对象(内存)。尝试重构此代码。

套接字聊天 -> http://socket.io/blog/native-socket-io-and-android/

关于android 私有(private)聊天自动刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078382/

相关文章:

android - 使用 Google Cloud Messaging 在 Android 上进行即时通讯

android - 添加谷歌服务 - 任务 ':app:processDebugResources' 执行失败

java - 在 Android (JAVA) 中对字符串使用 XPath

android - 多个 AsyncHttpClient 获取填充一个 Activity 的请求

android - RecyclerView 在 SoftKeyboard 可见时隐藏 Toolbar 和布局

MySQL SUM()、COUNT() 和 GROUP BY

java - 通过 AndEngine 触摸旋转

php - 动态模板表?

mysql - Node.js 在使用变量之前尝试使用 async/await 从 mysql select 获取数据

java - 通过 FCM onMessageReceived 方法从 RemoteMessage 获取值