[英]Messaging: If there is not connection, send message when recover it
I have created an instant messaging app for Android. 我已经为Android创建了一个即时消息应用程序。 But now I want to add some functionality: 但是现在我想添加一些功能:
If the users have not internet connection at the moment they try to send the message, it will have to be sent when the users recover the connection. 如果用户在尝试发送消息时没有互联网连接,则必须在用户恢复连接时发送该消息。
I guess the best way to do it is with a broadcast receiver. 我想最好的方法是使用广播接收器。 But I am not sure. 但我不确定。
EDIT: You could keep track of all the fail requests once the connection fails and set a thread who runs in the background that tries to send the failed messages. 编辑:一旦连接失败,您可以跟踪所有失败请求,并设置一个在后台运行的线程,该线程尝试发送失败的消息。 Let's say every 10-20 seconds or more. 假设每10-20秒或更长时间。 And if fails the thread goes to sleep. 如果失败,线程将进入睡眠状态。 Once all the messages are sent you close the thread and a new thread starts only if a message fails. 发送完所有消息后,您关闭线程,只有消息失败时才启动新线程。 if another message fails you check int he Queue. 如果另一条消息失败,则检查in Queue。 You could also use of PriorityQueue to schedule the messages in a easier way 您还可以使用PriorityQueue以更简单的方式安排消息
You can Get the Network State like this. 您可以像这样获取网络状态。
public boolean getInternetState() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
} else {
DialogFragment noInternet = new NoInternetDialog();
noInternet.show(getFragmentManager(), "noInternet");
return false;
}
}
And the you can show a DialogFragment to the user which will take him to wifi-settings or wherever you want. 然后,您可以向用户显示DialogFragment,这将带他进入wifi设置或您想要的任何位置。
public class NoInternetDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("No Internet Connection! Please Check your Internet Connection and try Again!")
.setPositiveButton("Open Wi-fi Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
} }
if(getInternetState()) {
// do network request here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.