延迟应用程序关闭并发送消息

时间:2017-07-18 14:21:13

标签: android sockets tcp

实际上我有 TCP客户端,onStart连接到服务器并将设备IP和号码发送给它,但现在我希望在应用程序关闭时(onDestroy)延迟一些秒(重新打开连接并发送另一条消息的正确时间)并发送另一条消息,其中我说该设备处于离线状态。

我已经尝试过onDestroy方法,但可能是它的疯狂,显然 那是行不通的(我试着在Destroy上做以下的事情:

protected void onDestroy() {
    new ConnectTask().execute("");
    if (client != null) {
        client.sendMessage(trm + "OFFLINE");
    }
    if (client != null) {
        client.stopClient();
    }

    super.onDestroy();
    server.onDestroy();
}

以下是我的 MainActivity 代码,我将调用TCP客户端并发送启动消息:

public class MainActivity extends AppCompatActivity {
Server server;
static Client client;
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
static TextView msgServer;
static String ipp;
static String trm;
static DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
        "Via Beniamino Disraeli, 17,\n" +
        "42124 Reggio Emilia \n" +
        "Telefono: 0522 / 38 32 22 \n" +
        "Fax: 0522 / 38 32 72 \n" +
        "Partita IVA, Codice Fiscale \n" +
        "Reg. Impr. di RE 00168780351 \n" +
        "Cap. soc. € 50.000,00 i.v. \n" + "" +
        "REA n. RE-107440 \n" +
        "presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Utils.darkenStatusBar(this, R.color.colorAccent);
    server = new Server(this);
    myDB = DataBaseHandler.getInstance(this);

    msg = (TextView) findViewById(R.id.msg);
    log = (TextView) findViewById(R.id.log_avviso);
    settings = (ImageButton) findViewById(R.id.impo);
    helps = (ImageButton) findViewById(R.id.aiut);
    allerts = (ImageButton) findViewById(R.id.msge);
    home = (ImageButton) findViewById(R.id.gab);
    terminale = (TextView) findViewById(R.id.terminal);
    indr = (TextView) findViewById(R.id.indr);
    msgServer = (TextView) findViewById(R.id.serverMSG);

    final Cursor cursor = myDB.fetchData();
    if (cursor.moveToFirst()) {
        do {
            indr.setText(cursor.getString(1));
            terminale.setText(cursor.getString(2));
            Client.SERVER_IP = cursor.getString(1);
            trm = cursor.getString(2);
        } while (cursor.moveToNext());
    }


    startService(new Intent(MainActivity.this,FinalizingOperationsService.class));

    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

    startConnection.postDelayed(runnableConnection,5000);
    startMessage.postDelayed(runnableMessage,5500);

    cursor.close();
    server.Parti();


    home.setOnClickListener(new View.OnClickListener() {
                                int counter = 0;
        @Override
        public void onClick(View view) {
                                    counter++;
                                    if (counter == 10) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                        builder.setCancelable(true);
                                        builder.setMessage(s1);
                                        builder.show();
                                        counter = 0;
                                    }
        }
    });

    settings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
            startActivity(impostazioni);
        }
    });

    helps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent pgHelp = new Intent(getApplicationContext(), help.class);
            startActivity(pgHelp);
        }
    });

    allerts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Server.count = 0;
            SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            editor.apply();
            msg.setVisibility(View.INVISIBLE);
            Intent pgAlert = new Intent(getApplicationContext(), allert.class);
            startActivity(pgAlert);
        }
    });

}

@Override
protected void onDestroy() {
    super.onDestroy();
    server.onDestroy();
}

public static class ConnectTask extends AsyncTask<String, String, Client> {

    @Override
    protected Client doInBackground(String... message) {


        client = new Client(new Client.OnMessageReceived() {
            @Override

            public void messageReceived(String message) {

                publishProgress(message);

            }
    });
        client.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

            msgServer.setTextColor(Color.parseColor("#00FF00"));
            msgServer.setText("ONLINE");

        Log.d("test", "response " + values[0]);
    }
}

static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
    @Override
    public void run() {

        new ConnectTask().execute("");
    }
};

static Handler startMessage = new Handler();
static Runnable runnableMessage = new Runnable() {
    @Override
    public void run() {
        final Cursor cursor = myDB.fetchData();
        if (cursor.moveToFirst()) {
            do {
                Client.SERVER_IP = cursor.getString(1);
                trm = cursor.getString(2);
            } while (cursor.moveToNext());
        }
        if (client != null) {
            client.sendMessage(ipp + "#" + trm);
        }
    }
};

static Handler startMessageClose = new Handler();
static Runnable runnableMessageClose = new Runnable() {
    @Override
    public void run() {
        if (client != null) {
            client.sendMessage(trm + "IS OFFLINE");
        }
        }
    };


}

打开连接的正确命令是new ConnectTask().execute(""); 我正在使用if (client != null) { client.sendMessage(ipp + "#" + trm); }

发送邮件

FinalizingOperationsService.java代码:

public class FinalizingOperationsService extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("FOService", "Service Started");
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d("FOService", "Service Destroyed");
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.e("FOService", "Service Ends");
    MainActivity.startConnection.removeCallbacks(MainActivity.runnableConnection);
    MainActivity.startConnection.postDelayed(MainActivity.runnableConnection,100);

    MainActivity.startMessageClose.removeCallbacks(MainActivity.runnableMessageClose);
    MainActivity.startMessageClose.postDelayed(MainActivity.runnableMessageClose,110);

    stopSelf();
    }
}

1 个答案:

答案 0 :(得分:1)

创建一个像这样的新服务,

public class FinalizingOperationsService extends Service {

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d("FOService", "Service Started");
            return START_STICKY;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d("FOService", "Service Destroyed");
        }

        @Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.e("FOService", "Service Ends");
            // write server updation code here
            // after completing code perform stopself() to stop this service;
        }
    }

在清单文件中定义此服务,如下所示,

<service android:name=". FinalizingOperationsService" android:stopWithTask="false"/>

最后在主要活动的onCreate方法中启动服务

startService(newIntent(getContext(),FinalizingOperationsService.class));

<强>说明: 当应用程序被终止或销毁时,将调用该服务的onTaskRemoved()方法,因此在此方法中,您可以执行最终操作以通知服务器并在操作完成后停止服务。希望它会对你有所帮助。