Android判断网络状态是否断开

1、Android判断网络状态是否断开
     不多说了,看代码吧!
/**
* 判断网络状态是否可用
* @return true: 网络可用 ; false: 网络不可用
*/

public boolean isConnectInternet() {
     ConnectivityManager conManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE );
     NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
     if (networkInfo != null ){ // 注意,这个判断一定要的哦,要不然会出错
         return networkInfo.isAvailable();
     }

     return false ;
}

最后别忘要在加上

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

这个权限哦!

 

2、Android完全关闭应用程序

在工作过程序中遇到一个需要完全关闭应用程序的问题,在网络上找了一大堆的文章,每篇都是用System.exit(0) 或者android.os.Process.killProcess(android.os.Process.myPid()) 这两种方法,但是我试过了, System.exit(0) 这个根本不行,而 android.os.Process.killProcess(android.os.Process.myPid()) 这个只能关闭当前的 Activity ,也就是对于一个只有单个 Activity 的应用程序有效,如果对于有多外 Activity 的应用程序它就无能为力了。
下面我介绍一下对于多个 Activity 的应用程序的完全关闭方法:

在 ActivityManager 类中提供了如下的方法:

/**
* Have the system perform a force stop of everything associated with
* the given application package. All processes that share its uid
* will be killed, all services it has running stopped, all activities
* removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
* broadcast will be sent, so that any of its registered alarms can * be stopped, notifications removed, etc.
*
* You must hold the permission * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to
* call this method.
*
* @param packageName The name of the package to be stopped.
*/

public void restartPackage(String packageName) {
    try {
        ActivityManagerNative.getDefault().restartPackage(packageName);
    }
    catch (RemoteException e) { }
}

 

所以如果要关闭整个应用程序的话只需要运行以下两行代码就行:

ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE );
activityMgr.restartPackage(getPackageName());


最后还需要添加这个权限才行:最后还需要添加这个权限才行:

<!-- 关闭应用程序的权限 -->
<uses-permission android:name="android.permission.RESTART_PACKAGES" />

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值