android私聊自动刷新

时间:2015-03-16 13:45:05

标签: android mysql google-cloud-messaging

我正在制作一个聊天应用程序,我希望私聊快,因为我正在使用自动刷新和asyntask。但是当我第一次去聊天课时它快速刷新但是当我回去并回来时再次,它变慢,需要时间刷新...并向数据库发送消息很慢。

如果我使用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/,但教程是关于群聊...............它们无论如何都要为私聊做插座... 。

1 个答案:

答案 0 :(得分:0)

你需要管理记忆。     慢速变得更频繁的垃圾收集器增加废物(内存)。尝试重构此代码。

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