在应用程序类Android App

时间:2016-11-29 16:56:52

标签: java android

我正在尝试在android中创建一个聊天应用程序,刚刚开始学习。它几乎完成了我想要的方式。 但是,我想解决两件事情以使其更好。

  1. 现在,我有一个应用程序类,它有一个线程可以连接到服务器。因此,当服务器脱机时,MainActivity布局不显示。它只显示一个白色屏幕。我可以从日志中看到它正在尝试连接到服务器。即使服务器处于脱机状态,是否可以显示MainActivity?

  2. 如何监控与服务器的连接?例如,在使用应用程序期间,如果服务器脱机,客户端应用程序崩溃。有办法阻止吗?我想要做的是,如果服务器崩溃,客户端将继续尝试再次连接到服务器。

  3. 以下是我现在正在处理的代码(MainActivity& Application Class)

    MyApplication.java

    package com.niyaz.chataway;
    
    public class Myapplication extends Application {
        public static boolean isfirstrun;
        public static Thread rthread,connectionthread;
        public static Socket socket;
        public static int SERVER_PORT;
        public static String SERVER_IP;
        public static BufferedReader br;
        public static BufferedWriter bw;
        public static String serverresponse;
    
        @Override
        public void onCreate(){
            super.onCreate();
            SERVER_IP = "192.168.1.116";
            SERVER_PORT= 62000;
            isfirstrun=true;
            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
    
            connectionthread = new connection(socket,SERVER_IP,SERVER_PORT);
           // connectionthread.start();
            connectionthread.run();
    
            rthread = new receive(this,socket,br);
            rthread.start();
        }
    
        public static void sendmessage(String message){
            try {
                bw.write(message);
                bw.newLine();
                bw.flush();
                System.out.println("Sent : " + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    class connection extends Thread{
        private Socket socket;
        private String serverip;
        private int serverport;
    
        public connection(Socket socket,String Serverip,int serverport){
            this.socket=socket;
            this.serverip=Serverip;
            this.serverport=serverport;
        }
    
        public void run(){
            while (true){
                try {
                    socket = new Socket(serverip,serverport);
                    System.out.println("Connection Established");
                    bw= new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    class receive extends Thread{
        private Socket socket;
        private BufferedReader br;
        private Handler handler = new Handler();
        String message;
        private Context context;
        public receive(Context context, Socket socket, BufferedReader br){
            this.socket = socket;
            this.br = br;
            this.context=context;
        }
    
        public void run(){
            while (true) {
                try {
                    message = br.readLine().toString();
                    System.out.println("Received message : " + message);
                    StringTokenizer token = new StringTokenizer(message, "|");
                    String a = token.nextToken();
                    String b = token.nextToken();
                    String c = token.nextToken();
                    switch (a) {
                        case "1": // get true or false from server
                            synchronized (this) {
                                MainActivity.response = b;
                                notify();
                                System.out.println("notified");
                            }
                            break;
                        case "2": // get group list from server
                            synchronized (this) {
                                System.out.println(b);
                                if (b.equals("end")){
                                    notify();
                                    System.out.println("notified");
                                    break;
                                }
                                group.all_groups.add(b);
                            }
    
                            break;
                        case "3": // get users in the group
                            synchronized (this) {
                                System.out.println(b);
                                if (b.equals("end")){
                                    notify();
                                    System.out.println("notified");
                                    break;
                                }
                                group.buffer.append(b);
                                group.buffer.append(System.getProperty("line.separator"));
    
                            }
                            break;
                        case "4":// get group size
                            synchronized (this) {
                                group.groupsize = Integer.valueOf(b);
                                notify();
                                System.out.println("notified");
                            }
                            break;
                        case "5": //  get chat messages from dB
                            synchronized (this) {
                                System.out.println(b);
                                if (b.equals("end")){
                                    notify();
                                    System.out.println("notified");
                                    break;
                                }
                                group.chatlist.add(b);
                            }
    
                            break;
                        case "6":// receive real time chat
                            final String temp = b;
                            final String t = c;
                            synchronized (this){
                                System.out.println("group_array.size()"+group.group_array.size());
    
                                for (int k = 0;k<group.group_array.size();k++){
                                    if (c.equals(group.group_array.get(k))){
                                        System.out.println(chatpage.checkactivity);
                                        if (chatpage.checkactivity){
                                            handler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    chatpage.adapter.add(temp);
                                                }
                                            });
                                            break;
                                        }
                                        if (!chatpage.checkactivity) {
                                            handler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                  //  Toast.makeText(context,"new message",Toast.LENGTH_SHORT).show();
                                                    MediaPlayer mp = MediaPlayer.create(context, R.raw.m);
                                                    mp.start();
    
    
                                                    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                                                    builder.setSmallIcon(android.R.drawable.sym_action_chat);
                                                    Intent intent = new Intent(context, group.class);
                                                    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
                                                    builder.setContentIntent(pendingIntent);
                                                    builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
                                                    builder.setContentTitle("New Message");
                                                    builder.setContentText(temp);
                                                    NotificationManager notificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
                                                    notificationManager.notify(1, builder.build());
    
    
                                                }
                                            });
    
                                            ArrayList<String> temp_array = new ArrayList<>();
                                            temp_array = group.map.get(c);
                                            temp_array.add(temp);
                                            group.map.put(c,temp_array);
    
                                            break;
                                        }
                                    }
                                }
                            }
    
                            break;
                        case "7":{   // get response from server
                            synchronized (this) {
                                serverresponse = b;
                                notify();
                                System.out.println("notified");
                            }
    
                            break;
                        }
                        case "8":{   // check if group already exist
                            synchronized (this) {
                                group.groupstatus = b;
                                notify();
                                System.out.println("notified");
                            }
    
                            break;
                        }
                        case "9": // get user grouplist
    
                            synchronized (this) {
                                System.out.println(b);
                                if (b.equals("end")){
                                    notify();
                                    System.out.println("notified");
                                    break;
                                }
                                group.group_array.add(b);
                            }
    
                            break;
                        default:
                            System.out.println("Why I am in default ??");
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    MainActivity.java

    package com.niyaz.chataway;
    
    public class MainActivity extends AppCompatActivity {
        Button login, register;
        EditText uname,upass;
        Myapplication myapplication;
        public static String response,name,password;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            uname=(EditText)findViewById(R.id.uname);
            upass=(EditText)findViewById(R.id.upass);
            login=(Button)findViewById(R.id.login);
            register=(Button)findViewById(R.id.register);
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            myapplication.isfirstrun=true;
            group.group_array = new ArrayList<>();
        }
    
        public void onclickmain(View view){
            Button b= (Button)view;
            name = uname.getText().toString();
            password=upass.getText().toString();
    
            if (b.getId()==R.id.login){
                if (name.isEmpty() || password.isEmpty()){
                    Toast.makeText(this,"User name or password cannot be blank",Toast.LENGTH_SHORT ).show();
                }
                else {
                    myapplication.sendmessage("1|" + name + "|" + password + "|" + null);
                    synchronized (myapplication.rthread){
                        try {
                            myapplication.rthread.wait();
                            System.out.println(response);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (response.equals("true")){
                        Intent intent = new Intent(getApplicationContext(),group.class);
                        startActivity(intent);
                    }
                    else {
                        Toast.makeText(this, "Username & Password do not match !", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    
            else if (b.getId()==R.id.register){
                if (name.isEmpty() || password.isEmpty()){
                    Toast.makeText(this,"User name or password cannot be blank", Toast.LENGTH_SHORT ).show();
                }
                else {
                    myapplication.sendmessage("2|" + name + "|" + password + "|" + null);
                    synchronized (myapplication.rthread){
                        try {
                            myapplication.rthread.wait();
                            System.out.println(myapplication.serverresponse);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (myapplication.serverresponse.equals("true")){
                        Toast.makeText(this, "User Registered Successfully !", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(this, "Try Again with different username !", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
    

    对于我的第二个问题,我在我的代码中添加了以下内容。如果服务器停机,现在我的应用程序重新连接。

    if( (message=br.readLine())==null){
                      handler.post(new Runnable() {
                          @Override
                          public void run() {
                              try {
                                  bw.close();
                                  br.close();
                              } catch (IOException e) {
                                  e.printStackTrace();
                              }
                              toolbar_group.setSubtitle("Network Down !");
                              connectionthread.run();
                          }
                      });
                      return;
                  }

    但是,只有在连接备份后才会调用以下内容。

     toolbar_group.setSubtitle("Network Down !");

    我想要一种方法向用户显示连接已关闭,请等待连接备份。 你能提出什么建议吗? 顺便说一下,我很感谢你的回复。我正在研究服务。现在,这将解决我的问题。

1 个答案:

答案 0 :(得分:0)

为了避免用一百万条评论来污染这个问题,我总结了一些好点并给你一些参考资料。

  1. 不要在Application中启动连接线程。这背后有很多原因。
  2. 如果您需要多线程,请使用AsyncTask,但要了解各种陷阱(而不是盲目地使用AsyncTask)。请记住,它会保留对您的活动的引用,因此如果使用不当,您可能会泄漏大量内存。
  3. 不要使用static字段,方法等,除非你真的有充分理由这样做;我还没有在你的代码中看到过一个。学习和阅读静态内存含义和多线程。
  4. 了解Android Service
  5. 使用Log.println
  6. 通过或多或少的Google约定,在您的私人字段前添加m(我不喜欢这样,但为了保持一致,我这样做),response成为mResponse
  7. 一些阅读材料:

    1. Application Fundamentals
    2. Services
    3. Lifecycle
    4. Processes and Threads
    5. 从这些开始,并提高您的Android技能;-)慢慢来。