在后台检查网络连接

3

我需要在后台检查网络连接...... 我正在保存一些数据到我的数据库中,每当我有互联网连接时, 它应该上传数据到我的服务器上... 我需要一个后台服务来持续检查互联网连接,即使我关闭了我的应用程序, 我尝试了几种方法,但它们只在我打开应用程序时工作... 目前,我像这样检查互联网连接

/checking internet connection

    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {

        //we are connected to a network
        connected = true;

    }
    else
       //not connected to internet
        connected = false;

    if(connected) {
        //getting teacher data if INTERNET_STATE is true(if will be still true if connected to a wifi or network without internet)
        getOfflineSubjectData();
        getTeacherData();
    }
    else{
        getOfflineSubjectData();
        Toast.makeText(teacher_homePage.this,"no internet",Toast.LENGTH_SHORT).show();
    }

注意:我不希望使用一种在关闭应用程序后无法工作的方法,就像WhatsApp一样,即使我们关闭应用程序,仍然可以收到文本消息。


当应用程序关闭时,您必须防止您的服务被终止。 - Vivek Mishra
你能提供一个例子吗? - Hena Shiekh
在你的服务的onDestroy()方法中重启你的服务。 - Vivek Mishra
发布您的服务代码或广播接收器,您可以使用它来代替。 - Ajay Pandya
请查看这个教程,它有非常好的解释。http://www.androidhive.info/2012/07/android-detect-internet-connection-status/ - Aman Shekhar
显示剩余2条评论
5个回答

6

我知道回答你的问题已经太晚了,但这仍是一个完美有效的解决方案。

我们可以通过同时使用服务和广播接收器来轻松地获得所需的输出。这将始终起作用,即当应用程序正在运行、应用程序被最小化或甚至从最小化的应用程序中删除时。

  1. Manifest Code :

    <application
    ...
    <service android:name=".MyService" />
    </application>
    
  2. MyService.java

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    import android.widget.Toast;
    
    public class MyService extends Service {
    
    static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    NotificationManager manager ;
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
                    //check internet connection
                    if (!ConnectionHelper.isConnectedOrConnecting(context)) {
                        if (context != null) {
                            boolean show = false;
                            if (ConnectionHelper.lastNoConnectionTs == -1) {//first time
                                show = true;
                                ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                            } else {
                                if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
                                    show = true;
                                    ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                                }
                            }
    
                            if (show && ConnectionHelper.isOnline) {
                                ConnectionHelper.isOnline = false;
                                Log.i("NETWORK123","Connection lost");
                                //manager.cancelAll();
                            }
                        }
                    } else {
                        Log.i("NETWORK123","Connected");
                        showNotifications("APP" , "It is working");
                        // Perform your actions here
                        ConnectionHelper.isOnline = true;
                    }
                }
            }
        };
        registerReceiver(receiver,filter);
        return START_STICKY;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
    }
    
  3. ConnectionHelper.java

    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    
    public class ConnectionHelper {
    
    public static long lastNoConnectionTs = -1;
    public static boolean isOnline = true;
    
    public static boolean isConnected(Context context) {
    ConnectivityManager cm =(ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    
    return activeNetwork != null && activeNetwork.isConnected();
    }
    
    public static boolean isConnectedOrConnecting(Context context) {
    ConnectivityManager cm =(ConnectivityManager)         context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    
    return activeNetwork != null &&
    activeNetwork.isConnectedOrConnecting();
    }
    
    }
    
  4. Your Activity Code

    startService(new Intent(getBaseContext(), MyService.class));
    

当应用程序处于被杀死状态时,这个功能不起作用吗? - Anubhav

5
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

public class CheckConnectivity extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent arg1) {

    boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }

安卓清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.connect.broadcast"
  android:versionCode="1"
  android:versionName="1.0" >

  <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>

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

  <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
       <receiver android:exported="false"
          android:name=".CheckConnectivity" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
     </receiver>
   </application>
</manifest>

主活动在这里什么也不做,我们在广播接收器中获取连接状态(与WhatsApp获取消息相同)。 - anshuVersatile
1
这不是我想要的...我想要一个在后台运行的服务,可以检查互联网连接...这将非常有帮助...就像 WhatsApp 一样...如果我们关闭它...我们仍然可以接收消息。 - Hena Shiekh
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - anshuVersatile
你找到解决方案了吗?我也遇到了同样的问题。 - Shuchi Sheth
请问@ShuchiSheth,在Android应用程序中,当我退出应用程序时,服务为什么会停止? - anshuVersatile

0

也许有更好的方法,但我按照@Rahul的建议实现了一个STICK_SERVICE,并且为了避免杀死该服务,在状态栏中强制显示了一个固定的通知。我知道这可能不是一个好习惯,但是客户要求在状态栏中显示“应用程序正在运行...”,所以没问题。

SyncService.class

public class SyncService extends IntentService {

    private static int FOREGROUND_ID = 1338;
    public Boolean isServiceRunning = false;
    Integer delay;
    private NotificationManager mgr;

    public SyncService() {
        super("SyncService");
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        performSync();
        startSyncThread();
        mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        final NotificationCompat.Builder builder = buildForeground();
        startForeground(1, builder.build());
        return START_STICKY;
    }

    public Boolean isWifiConnected() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

    public void startSyncThread() {
        Handler handler = new Handler();
        delay = 1000;

        handler.postDelayed(new Runnable() {
            public void run() {
                performSync();
                handler.postDelayed(this, delay);
            }
        }, delay);
    }

    public void performSync() {
        if (isWifiConnected()) {
            Log.i("SyncService:", "Wifi connected, start syncing...");
            Sync sync = new Sync(this);
            sync.postPhotos();
            sync.postEvents();
            sync.getEvents();
            delay = 60000;
        } else {
            Log.i("SyncService:", "Wifi IS NOT connected, ABORT syncing...");
            delay = 1000;
        }
        Log.i("SyncService:", delay + "");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        WakefulReceiver.completeWakefulIntent(intent);
    }


    private NotificationCompat.Builder buildForeground() {
        Intent intent = new Intent(this, EventsActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder b = new NotificationCompat.Builder(this);

        b.setContentTitle("Prime Share is running")
                .setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
                .setOngoing(true)
                .setAutoCancel(false)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent);

        return (b);

    }

}

然后在我的第一个活动的onCreate中,我调用了这个:

context = this;
startSyncIntent = new Intent(this, SyncService.class);
startService(startSyncIntent);

-1
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

在任何地方使用这个方法

if (!isNetworkAvailable(this)) {

   } else {}

-2

代码使用计时器检查互联网访问,我已经为此创建了一个服务。 这是我第一次在 Stack 上发布......所以事先抱歉,因为我无法以良好的格式发布它。

    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 1000;
    public static String str_receiver = "pravin.service.receiver";
    Intent intent;
    DatabaseHandler dh=new DatabaseHandler(this);
    public CheckInternet(){

    }
    @Override
    public void onCreate()
    {
        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetInternetStatus(), 5, notify_interval);
        intent = new Intent(str_receiver);
    }
    private class TimerTaskToGetInternetStatus extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    icConnected();
                }
            });

        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onStart(Intent intent,int startid)
    {


    }
    public boolean icConnected()
    {
        Log.d("Called " , "INTERNET");
        ConnectivityManager connec =
                (ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        // Check for network connections
        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
                Log.d("INTERNET","TRUE");
                dh.getIssues();
                return true;
            // if connected with internet

            //makeText(this, " Connected ", LENGTH_LONG).show();
        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
                Log.d("INTERNET","FALSE");
                return false;
            //makeText(this, " Not Connected ", LENGTH_LONG).show();
        }
        return false;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接