【问题标题】:What is the best way checking users' internet connection to send notification when it is on?检查用户的互联网连接以在打开时发送通知的最佳方法是什么?
【发布时间】:2017-11-24 20:06:40
【问题描述】:

我是关于发送通知的新手。我了解 AlarmManager 以及在 AlarmManager 触发时显示通知。我获取一些网站,从这些网站收集信息并将它们插入到我的托管数据库中。

我计划创建一个 android 应用程序,一旦用户有互联网连接,它就会将其中的一些插入信息发送给用户。实际上,我真正想要实现的是发送通知,如 Facebook、Twitter 或 Instagram(你知道,当你打开连接时,cmets、转推、喜欢、提及等通知会在一分钟内发送)。我认为这可以通过在 AlarmManager 中每隔 2 或 5 分钟检查一次用户的连接来完成,但它看起来对电池不利。应该有一些更专业或合乎逻辑的解决方案。你能告诉我实现这一目标的方法吗?

注意:我不需要连接控制代码。我只需要知道我应该选择检查哪个时间范围。我应该使用警报管理器还是有其他东西来管理后台的时间范围?

【问题讨论】:

标签: android notifications alarmmanager android-notifications


【解决方案1】:

`您可以将这些行添加到您的清单中并制作一个接收器

<receiver android:name=".NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>`

并如下创建一个类

public class NetworkChangeReceiver 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 {

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

【讨论】:

  • 确实,没有必要每隔几分钟进行一次检查。通过实现BroadcastReceiver ,每次检测到连接更改(每次用户连接或断开无线网络或移动数据时)都会调用onReceive 方法。
  • 这将用于检查是否有网络连接。但如果网络连接已连接到互联网,则不会。
  • Yessss,这就是我要找的 :) 我将不得不为 N 或更高版本的 android 更改“android.net.conn.connectivity_change”。 N 和更高版本不推荐使用它。感谢您的代码,您拯救了我的一天 :)
【解决方案2】:

您可以通过添加这行代码来检查互联网连接,为了更好地理解,您应该创建所有活动的父类并将此代码放在那里,并在所有子活动中扩展 Base Activity(Parent) 并且每次它都会在创建任何活动时执行。

public boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }

【讨论】:

  • 其实我想知道我是如何管理检查时间范围的。每隔几分钟使用一次 AlarmManager,或者有什么更好的方法。但是感谢代码示例。
【解决方案3】:

试试下面的代码,希望能解决你的问题。

供参考:https://github.com/oscarjiv91/Android-Check-Internet-Connection

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class ConnectionService extends Service {

    // Constant
    public static String TAG_INTERVAL = "interval";
    public static String TAG_URL_PING = "url_ping";
    public static String TAG_ACTIVITY_NAME = "activity_name";

    private int interval;
    private String url_ping;
    private String activity_name;

    private Timer mTimer = null;

    ConnectionServiceCallback mConnectionServiceCallback;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public interface ConnectionServiceCallback {
        void hasInternetConnection();
        void hasNoInternetConnection();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        interval = intent.getIntExtra(TAG_INTERVAL, 10);
        url_ping = intent.getStringExtra(TAG_URL_PING);
        activity_name = intent.getStringExtra(TAG_ACTIVITY_NAME);

        try {
            mConnectionServiceCallback = (ConnectionServiceCallback) Class.forName(activity_name).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new CheckForConnection(), 0, interval * 1000);

        return super.onStartCommand(intent, flags, startId);
    }

    class CheckForConnection extends TimerTask{
        @Override
        public void run() {
            isNetworkAvailable();
        }
    }

    @Override
    public void onDestroy() {
        mTimer.cancel();
        super.onDestroy();
    }

    private boolean isNetworkAvailable(){
        HttpGet httpGet = new HttpGet(url_ping);
        HttpParams httpParameters = new BasicHttpParams();

        int timeoutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        int timeoutSocket = 7000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        try{
            httpClient.execute(httpGet);
            mConnectionServiceCallback.hasInternetConnection();
            return true;
        }
        catch(ClientProtocolException e){
            e.printStackTrace();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        mConnectionServiceCallback.hasNoInternetConnection();
        return false;
    }

}

在您的活动中,您要在哪里启动此服务:

Intent intent = new Intent(this, ConnectionService.class);
    // Interval in seconds
    intent.putExtra(ConnectionService.TAG_INTERVAL, 100);
    // URL to ping
    intent.putExtra(ConnectionService.TAG_URL_PING, "http://www.google.com");
    // Name of the class that is calling this service
    intent.putExtra(ConnectionService.TAG_ACTIVITY_NAME, this.getClass().getName());
    // Starts the service
    startService(intent);

在您的活动上实现 ConnectionService.ConnectionServiceCallback 并覆盖方法:

@Override
public void hasInternetConnection() {
   // has internet
}

@Override
public void hasNoInternetConnection() {
   // no internet :(
}

停止服务

stopService(new Intent(this, ConnectionService.class));

【讨论】:

  • 其实我想知道我是如何管理检查时间范围的。每隔几分钟使用一次 AlarmManager,或者有什么更好的方法。但是感谢代码示例。
  • @umitkilic 请检查我更新的答案,让我知道这就是你要找的。​​span>
猜你喜欢
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
相关资源
最近更新 更多