Android中的Android聊天应用程序

时间:2014-12-24 10:01:08

标签: java android

嗨在我的应用程序中我正在使用gcm开发android聊天功能,这是我的代码。我有两个字段名称和手机号码和按钮登录现在。

单击“登录”按钮,然后它将显示使用gcm后他将在线的人员,我可以发送消息。

但是点击登录按钮我很遗憾地收到错误并显示Service_not_Available它显示此消息。

任何人都可以帮我解决这个问题

MainActivity.java

public class MainActivity extends Activity {

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    String SENDER_ID = "689402109398";


    static final String TAG = "L2C";

    GoogleCloudMessaging gcm;
    SharedPreferences prefs;
    Context context;
    String regid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prefs = getSharedPreferences("Chat", 0);
        context = getApplicationContext();
        if(!prefs.getString("REG_FROM","").isEmpty()){
            Fragment user = new UserFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, user);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(null);
            ft.commit();
        }else  if(!prefs.getString("REG_ID", "").isEmpty()){
            Fragment reg = new LoginFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, reg);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(null);
            ft.commit();

        }else if(checkPlayServices()){

            new Register().execute();

        }else{
            Toast.makeText(getApplicationContext(),"This device is not supported",Toast.LENGTH_SHORT).show();
        }
    }
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }


    private class Register extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... args) {
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                    regid = gcm.register(SENDER_ID);
                    Log.e("RegId",regid);

                    SharedPreferences.Editor edit = prefs.edit();
                    edit.putString("REG_ID", regid);
                    edit.commit();

                }

                return  regid;

            } catch (IOException ex) {
                Log.e("Error", ex.getMessage());
                return "Fails";

            }
        }
        @Override
        protected void onPostExecute(String json) {
            Fragment reg = new LoginFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, reg);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(null);
            ft.commit();
        }
    }

UserFragmen.java

public class UserFragment extends Fragment {
    ListView list;
    ArrayList<HashMap<String, String>> users = new ArrayList<HashMap<String, String>>();
    Button refresh,logout;
    List<NameValuePair> params;
    SharedPreferences prefs;


    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.user_fragment, container, false);
        prefs = getActivity().getSharedPreferences("Chat", 0);

        list = (ListView)view.findViewById(R.id.listView);
        refresh = (Button)view.findViewById(R.id.refresh);
        logout = (Button)view.findViewById(R.id.logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new  Logout().execute();

            }
        });
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.content_frame)).commit();
                Fragment reg = new UserFragment();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, reg);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();

            }
        });
        new Load().execute();

        return view;
    }

    private class Load extends AsyncTask<String, String, JSONArray> {

        @Override
        protected JSONArray doInBackground(String... args) {
            JSONParser json = new JSONParser();
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
            JSONArray jAry = json.getJSONArray("http://10.0.2.2/getuser",params);

            return jAry;
        }
        @Override
        protected void onPostExecute(JSONArray json) {
            for(int i = 0; i < json.length(); i++){
                JSONObject c = null;
                try {
                    c = json.getJSONObject(i);
                    String name = c.getString("name");
                    String mobno = c.getString("mobno");
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("name", name);
                    map.put("mobno", mobno);
                    users.add(map);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            ListAdapter adapter = new SimpleAdapter(getActivity(), users,
                    R.layout.user_list_single,
                    new String[] { "name","mobno" }, new int[] {
                    R.id.name, R.id.mobno});
            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Bundle args = new Bundle();
                    args.putString("mobno", users.get(position).get("mobno"));
                    Intent chat = new Intent(getActivity(), ChatActivity.class);
                    chat.putExtra("INFO", args);
                    startActivity(chat);
                }
            });
        }
    }
    private class Logout extends AsyncTask<String, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser json = new JSONParser();
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
            JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2/chat/logout",params);

            return jObj;
        }
        @Override
        protected void onPostExecute(JSONObject json) {

            String res = null;
            try {
                res = json.getString("response");
                Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();
                if(res.equals("Removed Sucessfully")) {
                    Fragment reg = new LoginFragment();
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.content_frame, reg);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.addToBackStack(null);
                    ft.commit();
                    SharedPreferences.Editor edit = prefs.edit();
                    edit.putString("REG_FROM", "");
                    edit.commit();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }



        }
    }

** LoginFragment **

public class LoginFragment extends Fragment {
    SharedPreferences prefs;
    EditText name, mobno;
    Button login;
    List<NameValuePair> params;
    ProgressDialog progress;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_fragment, container, false);
        prefs = getActivity().getSharedPreferences("Chat", 0);
        name = (EditText)view.findViewById(R.id.name);
        mobno = (EditText)view.findViewById(R.id.mobno);

        login = (Button)view.findViewById(R.id.log_btn);
        progress = new ProgressDialog(getActivity());
        progress.setMessage("Registering ...");
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);



        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progress.show();
                SharedPreferences.Editor edit = prefs.edit();

                edit.putString("REG_FROM", mobno.getText().toString());
                edit.putString("FROM_NAME", name.getText().toString());
                edit.commit();
                new Login().execute();
            }
        });

        return view;
    }
    private class Login extends AsyncTask<String, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser json = new JSONParser();
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name.getText().toString()));
            params.add(new BasicNameValuePair("mobno", mobno.getText().toString()));
            params.add((new BasicNameValuePair("reg_id",prefs.getString("REG_ID",""))));

            JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2/login",params);
            return jObj;



        }
        @Override
        protected void onPostExecute(JSONObject json) {
            progress.dismiss();
            try {
                String res = json.getString("response");
                if(res.equals("Sucessfully Registered")) {
                    Fragment reg = new UserFragment();
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.content_frame, reg);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.addToBackStack(null);
                    ft.commit();
                }else{
                    Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();

                }

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

        }
    }

logcat的

12-24 03:26:46.087: E/Error(1915): SERVICE_NOT_AVAILABLE

12-24 03:28:52.087: W/System.err(1939): org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8660 refused
12-24 03:28:52.147: W/System.err(1939):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
12-24 03:28:52.147: W/System.err(1939):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-24 03:28:52.147: W/System.err(1939):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-24 03:28:52.177: W/System.err(1939):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:452)
12-24 03:28:52.177: W/System.err(1939):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-24 03:28:52.187: W/System.err(1939):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-24 03:28:52.187: W/System.err(1939):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-24 03:28:52.187: W/System.err(1939):     at com.example.androidchat.JSONParser.getJSONFromUrl(JSONParser.java:41)
12-24 03:28:52.187: W/System.err(1939):     at com.example.androidchat.LoginFragment$Login.doInBackground(LoginFragment.java:74)
12-24 03:28:52.187: W/System.err(1939):     at com.example.androidchat.LoginFragment$Login.doInBackground(LoginFragment.java:1)
12-24 03:28:52.187: W/System.err(1939):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-24 03:28:52.337: W/System.err(1939):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-24 03:28:52.347: W/System.err(1939):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-24 03:28:52.377: W/System.err(1939):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-24 03:28:52.377: W/System.err(1939):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-24 03:28:52.387: W/System.err(1939):     at java.lang.Thread.run(Thread.java:841)
12-24 03:28:52.387: W/System.err(1939): Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 8660): connect failed: ETIMEDOUT (Connection timed out)
12-24 03:28:52.407: I/Choreographer(1939): Skipped 30 frames!  The application may be doing too much work on its main thread.
12-24 03:28:52.427: W/System.err(1939):     at libcore.io.IoBridge.connect(IoBridge.java:114)
12-24 03:28:52.437: W/System.err(1939):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-24 03:28:52.437: W/System.err(1939):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-24 03:28:52.437: W/System.err(1939):     at java.net.Socket.connect(Socket.java:843)
12-24 03:28:52.437: W/System.err(1939):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-24 03:28:52.437: W/System.err(1939):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-24 03:28:52.437: W/System.err(1939):     ... 15 more
12-24 03:28:52.497: I/Choreographer(1939): Skipped 52 frames!  The application may be doing too much work on its main thread.
12-24 03:28:52.617: I/Choreographer(1939): Skipped 30 frames!  The application may be doing too much work on its main thread.
12-24 03:28:52.947: W/System.err(1939): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
12-24 03:28:53.007: I/Choreographer(1939): Skipped 36 frames!  The application may be doing too much work on its main thread.
12-24 03:28:53.087: I/Choreographer(1939): Skipped 30 frames!  The application may be doing too much work on its main thread.
12-24 03:28:53.117: W/System.err(1939):     at libcore.io.Posix.connect(Native Method)
12-24 03:28:53.117: W/System.err(1939):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
12-24 03:28:53.117: W/System.err(1939):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-24 03:28:53.117: W/System.err(1939):     at libcore.io.IoBridge.connect(IoBridge.java:112)
12-24 03:28:53.117: W/System.err(1939):     ... 20 more
12-24 03:28:53.117: E/Buffer Error(1939): Error converting result java.lang.NullPointerException: lock == null
12-24 03:28:53.187: I/Choreographer(1939): Skipped 62 frames!  The application may be doing too much work on its main thread.
12-24 03:28:53.457: E/JSON Parser(1939): Error parsing data org.json.JSONException: End of input at character 0 of 
12-24 03:28:53.497: I/Choreographer(1939): Skipped 36 frames!  The application may be doing too much work on its main thread.
12-24 03:28:53.697: D/AndroidRuntime(1939): Shutting down VM
12-24 03:28:53.697: W/dalvikvm(1939): threadid=1: thread exiting with uncaught exception (group=0xb2ae2ba8)
12-24 03:28:53.807: E/AndroidRuntime(1939): FATAL EXCEPTION: main
12-24 03:28:53.807: E/AndroidRuntime(1939): Process: com.example.androidchat, PID: 1939
12-24 03:28:53.807: E/AndroidRuntime(1939): java.lang.NullPointerException
12-24 03:28:53.807: E/AndroidRuntime(1939):     at com.example.androidchat.LoginFragment$Login.onPostExecute(LoginFragment.java:84)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at com.example.androidchat.LoginFragment$Login.onPostExecute(LoginFragment.java:1)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at android.os.Looper.loop(Looper.java:136)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at android.app.ActivityThread.main(ActivityThread.java:5017)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at java.lang.reflect.Method.invokeNative(Native Method)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at java.lang.reflect.Method.invoke(Method.java:515)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-24 03:28:53.807: E/AndroidRuntime(1939):     at dalvik.system.NativeStart.main(Native Method)
12-24 03:28:58.477: I/Process(1939): Sending signal. PID: 1939 SIG: 9
12-24 03:29:05.277: D/dalvikvm(1976): GC_FOR_ALLOC freed 114K, 7% free 2849K/3036K, paused 183ms, total 187ms
12-24 03:29:06.027: I/Choreographer(1976): Skipped 73 frames!  The application may be doing too much work on its main thread.
12-24 03:29:06.067: D/gralloc_goldfish(1976): Emulator without GPU emulation detected.
12-24 03:29:06.267: I/Choreographer(1976): Skipped 152 frames!  The application may be doing too much work on its main thread.
12-24 03:29:07.187: D/dalvikvm(1976): GC_FOR_ALLOC freed 118K, 6% free 3242K/3428K, paused 34ms, total 34ms

0 个答案:

没有答案