ANDROID Internet/GPS 断开连接或未连接时显示对话框
ANDROID Show a dialog when the Internet/GPS loses connectivity or is not connected
[已编辑]
我想在 Internet 或 GPS 断开或未连接时显示启动画面/对话框,以便用户在连接恢复正常之前无法使用该应用程序。
我试过一些广播接收器,但都有问题。其中之一:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
if(status.equals("Not connected to Internet")) {
Intent splashIntent = new Intent(context, SplashScreen.class);
splashIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(splashIntent);
//I also had a Toast for internet is connected
}
}
}
和 util 类:
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
问题:它不能立即生效。当互联网断开连接时,我通常连续获得 5 个吐司,一段时间后,如果我修改状态,连接吐司停止出现或在等待很长时间后出现。
另外,网络恢复后如何关闭启动画面activity?
尝试以下解决方案
第 1 步:
创建一个名为 NetworkStatus
的 Java Class
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkStatus
{
Context context;
public NetworkStatus(Context context)
{
this.context = context;
}
public boolean isNetworkOnline()
{
boolean status = false;
try
{
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
{
status = true;
}
else
{
netInfo = cm.getNetworkInfo(1);
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
{
status = true;
}
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return status;
}
}
第 2 步:
创建另一个 Class
命名为 AlertDialogManager
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import com.lmkt.wfm.R;
import com.lmkt.wfm.activities.ActivityMainScreen;
public class AlertDialogManager
{
Context context;
public AlertDialogManager(Context context)
{
this.context = context;
}
public void showAlertDialog(String title, final String message, final Boolean status)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
if(status != null)
{
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
}
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
if(message.contains("You do not have Internet Connection"))
{
((Activity) context).finish();
}
dialog.dismiss();
}
});
alertDialog.show();
}
}
第 3 步:使用 Splash Activity:
AlertDialogManager alert;
NetworkStatus ns;
ns = new NetworkStatus(context);
if(!(ns.isNetworkOnline()))
{
alert = new AlertDialogManager(context);
alert.showAlertDialog("Internet Connection!", "You do not have Internet Connection. "
+ "Please connect to the "
+ "Internet to sync Data From Server...", false);
}
你可以创建一个 Service
class 并使用 TimerTask
和 Timer
并给它一个重新开始的持续时间,这样你就可以开始你的 service
来自你已经拥有的 receiver
并使其 (receiver
) 收听 BOOT_COMPLETED
和
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
并指定权限 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
并让您的接收器调用服务 class -(或者您可以在那里检查您的东西 -(考虑我所做的评论))通过在您的 onReceive
boolean isMyServiceRunning(Class<?> serviceClass, Context t) {
ActivityManager manager = (ActivityManager) t.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
如果它returns错误启动服务使用
Intent i = new Intent(context, MyService.class);
context.startService(i);
然后在您的服务中执行此操作
public class MyService extends Service {
Timer timer; TimerTask task;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
// put here your code for checking
String status = NetworkUtil.getConnectivityStatusString(context);
// i am having nesting problems so put this in a handler() ok
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
if(status.equals("Not connected to Internet")) {
Intent splashIntent = new Intent(context, SplashScreen.class);
splashIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(splashIntent);
}
// handler() code should end here
};
timer.schedule(task, 0, 3000); // repeat every 3 seconds
return START_STICKY;
}
}
它越来越长,要关闭启动画面,您可以传递 activity 的实例并使其从服务中自行关闭,或者绑定到服务或使用本地广播管理器
我的代码结束标记也可能有误,请更正它们..
第 1 步:
打开AndroidManifest.xml并添加广播接收器。
<receiver
android:name=".Util.InternetConnectorReceiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>`
第 2 步: 创建 activity 对话主题:
<activity
android:name=".Activity.ActivityDialogInternet"
android:theme="@style/AppTheme.Dark.Dialog"></activity>
第 3 步:
创建一个名为 InternetConnectorReceiver
的 BroadcastReceiver Class
public class InternetConnectorReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED) ||
intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
Intent checkIntent = new Intent(context, ConnectivityCheck.class);
context.startService(checkIntent);
}
}}
第 4 步: 创建另一个名为 ConnectivityCheck 的服务 class :
public class ConnectivityCheck extends Service {
@Override
public void onCreate() {
super.onCreate();
if (!checkConnection()) {
Toast.makeText(context, "off", Toast.LENGTH_LONG).show();
Intent dialogIntent = new Intent(this, ActivityDialogInternet.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
stopSelf();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private boolean checkConnection() {
Log.i("wudfuyf", "checking started!!!!!!!!!!!!!!!!!!");
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}}
第 5 步: 创建一个名为 ActivityDialogInternet
的 activity
public class ActivityDialogInternet extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_internet);
}}
第 6 步: 当互联网连接关闭时 ActivityDialogInternet 调用并显示对话框:
[已编辑]
我想在 Internet 或 GPS 断开或未连接时显示启动画面/对话框,以便用户在连接恢复正常之前无法使用该应用程序。
我试过一些广播接收器,但都有问题。其中之一:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
if(status.equals("Not connected to Internet")) {
Intent splashIntent = new Intent(context, SplashScreen.class);
splashIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(splashIntent);
//I also had a Toast for internet is connected
}
}
}
和 util 类:
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
问题:它不能立即生效。当互联网断开连接时,我通常连续获得 5 个吐司,一段时间后,如果我修改状态,连接吐司停止出现或在等待很长时间后出现。
另外,网络恢复后如何关闭启动画面activity?
尝试以下解决方案
第 1 步:
创建一个名为 NetworkStatus
Java Class
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkStatus
{
Context context;
public NetworkStatus(Context context)
{
this.context = context;
}
public boolean isNetworkOnline()
{
boolean status = false;
try
{
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
{
status = true;
}
else
{
netInfo = cm.getNetworkInfo(1);
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
{
status = true;
}
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return status;
}
}
第 2 步:
创建另一个 Class
命名为 AlertDialogManager
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import com.lmkt.wfm.R;
import com.lmkt.wfm.activities.ActivityMainScreen;
public class AlertDialogManager
{
Context context;
public AlertDialogManager(Context context)
{
this.context = context;
}
public void showAlertDialog(String title, final String message, final Boolean status)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
if(status != null)
{
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
}
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
if(message.contains("You do not have Internet Connection"))
{
((Activity) context).finish();
}
dialog.dismiss();
}
});
alertDialog.show();
}
}
第 3 步:使用 Splash Activity:
AlertDialogManager alert;
NetworkStatus ns;
ns = new NetworkStatus(context);
if(!(ns.isNetworkOnline()))
{
alert = new AlertDialogManager(context);
alert.showAlertDialog("Internet Connection!", "You do not have Internet Connection. "
+ "Please connect to the "
+ "Internet to sync Data From Server...", false);
}
你可以创建一个 Service
class 并使用 TimerTask
和 Timer
并给它一个重新开始的持续时间,这样你就可以开始你的 service
来自你已经拥有的 receiver
并使其 (receiver
) 收听 BOOT_COMPLETED
和
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
并指定权限 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
并让您的接收器调用服务 class -(或者您可以在那里检查您的东西 -(考虑我所做的评论))通过在您的 onReceive
boolean isMyServiceRunning(Class<?> serviceClass, Context t) {
ActivityManager manager = (ActivityManager) t.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
如果它returns错误启动服务使用
Intent i = new Intent(context, MyService.class);
context.startService(i);
然后在您的服务中执行此操作
public class MyService extends Service {
Timer timer; TimerTask task;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
// put here your code for checking
String status = NetworkUtil.getConnectivityStatusString(context);
// i am having nesting problems so put this in a handler() ok
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
if(status.equals("Not connected to Internet")) {
Intent splashIntent = new Intent(context, SplashScreen.class);
splashIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(splashIntent);
}
// handler() code should end here
};
timer.schedule(task, 0, 3000); // repeat every 3 seconds
return START_STICKY;
}
}
它越来越长,要关闭启动画面,您可以传递 activity 的实例并使其从服务中自行关闭,或者绑定到服务或使用本地广播管理器
我的代码结束标记也可能有误,请更正它们..
第 1 步: 打开AndroidManifest.xml并添加广播接收器。
<receiver
android:name=".Util.InternetConnectorReceiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>`
第 2 步: 创建 activity 对话主题:
<activity
android:name=".Activity.ActivityDialogInternet"
android:theme="@style/AppTheme.Dark.Dialog"></activity>
第 3 步: 创建一个名为 InternetConnectorReceiver
的 BroadcastReceiver Classpublic class InternetConnectorReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED) ||
intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
Intent checkIntent = new Intent(context, ConnectivityCheck.class);
context.startService(checkIntent);
}
}}
第 4 步: 创建另一个名为 ConnectivityCheck 的服务 class :
public class ConnectivityCheck extends Service {
@Override
public void onCreate() {
super.onCreate();
if (!checkConnection()) {
Toast.makeText(context, "off", Toast.LENGTH_LONG).show();
Intent dialogIntent = new Intent(this, ActivityDialogInternet.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
stopSelf();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private boolean checkConnection() {
Log.i("wudfuyf", "checking started!!!!!!!!!!!!!!!!!!");
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}}
第 5 步: 创建一个名为 ActivityDialogInternet
的 activitypublic class ActivityDialogInternet extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_internet);
}}
第 6 步: 当互联网连接关闭时 ActivityDialogInternet 调用并显示对话框: