2017-07-18 98 views
0

其实我有一个TCP客户端 onStart连接到服务器并发送设备的IP和号码给它,但现在我想,当应用程序正在关闭(onDestroy)延迟几秒钟(正确的时间重新打开连接并发送另一条消息),并发送另一条消息,其中我说设备处于脱机状态。延迟应用程序关闭并发送消息

我tryed做的onDestroy方法,但可能它的疯狂,显然 未工作(我tryed做以下的东西的onDestroy:

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

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

这里是我的MainActivity代码,其中我evocate的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

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

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"/> 

最后st在您的主要活动的onCreate方法艺术服务

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

说明: onTaskRemoved()服务的方法,当应用被杀死或破坏被调用,所以在这种方法中,你可以执行你的最终操作通知服务器并在操作完成后停止服务。希望它能帮助你。

+0

我只是尝试去做,但似乎没有任何改变,我已经用FInalizingOperationsService代码更新了问题,并且更新了MainActivity,你可以看看它吗? –

+0

我认为当应用程序关闭时,您失去了客户端的参考,您必须重新初始化您的客户端以执行这些操作。 – AndroidGeek

+0

等待,但我必须为FinalizingOperationsService创建一个新类吗?或者我可以在MainActivity中做到这一点?因为为了重新初始化我必须重新复制主 –