失去网络连接后如何以编程方式重新启动网络?

问题描述 投票:0回答:1

我有一个与Lan Adapter连接的Android设备,它非常随机地失去了连接。因此需要我重新启动网络或重新启动整个设备才能恢复正常工作。当我失去网络连接时,如何编程正在运行的Android应用程序以重新启动网络((如果可能,请重新启动Lan适配器或网络,否则请重新启动设备))。

例如,在Linux中,我们使用ifup和ifdown

android android-networking
1个回答
-1
投票
You will need to use broadcast receiver. You will continuously receive updates in connectivity.(Connected/Disconnected)
Example:
Manifest:
Permissions:
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Register broadcast receiver:
<receiver android:name=".ConnectivityChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
Create receiver class:
public class ConnectivityChangeReceiver extends BroadcastReceiver {


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

        // Explicitly specify that which service class will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                YourService.class.getName());
        intent.putExtra("isNetworkConnected",isConnected(context));
        startService(context, (intent.setComponent(comp)));
    }

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

}
Your service class:
class YourService extends IntentService{

    @Override
    protected void onHandleIntent(Intent intent) {
      Bundle extras = intent.getExtras();
      boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
      // your code

   }

}
© www.soinside.com 2019 - 2024. All rights reserved.