Android 连接时在后台发送数据 [英] Android Send data in the background when connected

查看:41
本文介绍了Android 连接时在后台发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要我的应用程序在与网络建立连接时向服务器发送一些数据,并且它必须在后台.就是这样.

Basicly I need that my app sends some data to a server when the connection to the network is established and it has to be in the background. That's it.

有没有办法在建立连接时自动启动我的服务?或者我应该使用常规服务来测试连接并以 30 分钟的间隔运行此服务?我应该使用 AlarmManager 之类的东西来检查连接吗?这似乎是对资源的浪费,据我所知,如果需要资源,Android 可以停止服务.

Is there a way that my service is automaticly started when connection is made? Or should I use regular Service which tests the connection and run this service in something like 30min intervals? Should I use something like the AlarmManager to check for the connection? This seems as a waste of the resources and as far as I'm aware Android can stop services if resources are needed.

有什么建议或者更好的 - 关于最佳方法的示例?

Any suggestions or even better - samples on what is the optimal way?

谢谢.

推荐答案

您可以为此使用 广播接收器.请参阅关于 SO 的这个问题.

You can use a broadcast receiver for this purpose. See this question on SO.

您可以检查互联网连接是否已建立,无需定期检查.

You can check if internet connection has been established, there is no need to check after regular intervals.

(引用我之前提到的链接)

(Quoting from the link I have mentioned earlier)

<receiver android:name=".ReceiverName" >
    <intent-filter >
        <action android:name="android.net.wifi.STATE_CHANGE" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

public class ReceiverName extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        if (cm == null)
            return;
        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
            // Send here
        } else {
            // Do nothing or notify user somehow
        }

    }
}

希望这会有所帮助!

这篇关于Android 连接时在后台发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆