私はアンドロイドでチャットアプリケーションを作成しようとしています。 しかし、それを改善するために解決したいことが2つあります。サーバはoffline.Itがちょうど白い画面を示しているときアプリケーションクラスで接続する前にMainActivityが開かないAndroid App
は今、私はこれにserver.Dueへの接続を行うためのスレッドを持つアプリケーションのクラスを持って、MainActivityレイアウトは現れていません。私はそれがサーバーに接続しようとしているログから見ることができます。サーバーがオフラインであってもMainActivityを表示することは可能ですか?
サーバへの接続をどのように監視できますか?たとえば、アプリケーションの使用中に、サーバーがオフラインになると、クライアントアプリケーションがクラッシュします。それを止める方法はありますか?私がしたいのは、サーバーがクラッシュした場合でも、クライアントはサーバーに再び接続しようとします。以下は
私は今働いている私のコード(MainActivity &アプリケーションクラス)私の第二のために
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 !");
私は接続がダウンしている、バックアップする接続を待機してくださいことをユーザーに表示する方法をしたいです。 何か提案してもらえますか? Btwは迅速な返信をいただき、ありがとうございます。私はサービスを探しています。今のところ、これは私の問題を解決するでしょう。
'MainActivity'に' Application'を拡張するのではなく、接続スレッドを生成することをお勧めします。後のオプションはコードの匂いとみなされます。また、マルチスレッド化のための 'AsyncTask'について学ぶ必要があります。それはあなたのための多くの詳細を処理します。 –
'static'メソッドと変数も、あまりオブジェクト指向ではないので、悪い習慣とみなされます。彼らは確かに使用しています。しかし、静的なものが正当化されていることを本当に理解する前に、オブジェクト指向の概念を学ぶ必要があります。 –
メインアクティビティでサーバ接続を開始し、 'Service'を使用してバックグラウンドで接続を維持し、Androidのサービスについて読むことができます。アクティビティからサービスを制御する(必要に応じてバインドする)。すべてのことを読んでください。正当な理由がない限り、静的フィールドを使用しないでください。ここにはありません。 System.out.printlnの代わりに 'Log.d'(またはそれに類するもの)を使用してください。等。 –