API挂钩连接变化

时间:2017-06-24 21:09:10

标签: android web-services service architecture

我在Android手机上有一个打印机检测应用程序,其基本检查表格为 即使没有互联网连接,Inspector也可以进行打印机检查,

一旦手机回到接收/互联网,我想提交检查。

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

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

我是否可以注册我的应用程序以通过互联网连接通知应用程序或服务?

1 个答案:

答案 0 :(得分:2)

简单检查 Wi-Fi 移动互联网,如下所示......

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();
    }
}


**不要忘记在清单文件中添加使用互联网的权限:

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



另请参阅vogella.com AndroidServices上的这篇超酷文章......