【问题标题】:API Hook on connectivity change连接更改的 API Hook
【发布时间】:2017-11-28 04:33:09
【问题描述】:

我在安卓手机上有一个打印机检查应用程序,它的基本检查表
即使没有互联网连接,Inspector 也可以进行打印机检查,

一旦电话恢复接收/上网,我想提交检查。

我正在考虑使用 android 服务设计应用程序
所以它将使用sqlite保存检查细节,然后在有互联网连接时重新提交检查。

但这需要服务定期检查互联网。并且会消耗大量电池电量。

我可以为我的应用注册一个钩子来通知应用或互联网连接上的服务吗?

【问题讨论】:

    标签: android web-services service architecture


    【解决方案1】:

    Wi-fiMobile 互联网的简单检查如下...

    Manifest.xml 中:

    <receiver android:name=".com.yourapp.ConnectivityChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>
    


    制作一个新的BroadcastReceiver

    public class ConnectivityChangeReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(final Context context, final Intent intent) {
    
            if(checkInternet(context))
            {
                Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
            }
    
        }
    
        boolean checkInternet(Context context) {
            ServiceManager serviceManager = new ServiceManager(context);
            if (serviceManager.isNetworkAvailable()) {
                return true;
            } else {
                return false;
            }
        }
    }
    


    最后是 ServiceManager 类:

    public class ServiceManager {
    
        Context context;
    
        public ServiceManager(Context base) {
            context = base;
        }
    
        public boolean isNetworkAvailable() {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
    }
    


    ** 不要忘记在您的 ma​​nifest 文件中添加使用 Internet 的权限:

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



    还可以在 vogella.com AndroidServices 上查看这篇超酷的文章 ...

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 2010-11-04
      • 2014-06-05
      相关资源
      最近更新 更多