Android Wi-Fi check on every onRestart

I want my application to check if the device connects to a specific Wi-Fi and automatically connects to Wi-Fi every time the application connects. I know I can do it in onRestart (). But it only processes one state of activity.

My question is, is there any method to handle the state of the application instead of adding onRestart () for each action to do what I want?

+4
source share
1 answer

try the following code:

import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; public class AutostartService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("in broad...."); ConnectivityManager manager = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE); boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); if(!is3g && !isWifi){ }else{ if ((intent.getAction() != null) && (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))) { System.out.println("in broadcast receiver....."); Intent i = new Intent(context, Splash.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } } } } 

Remember to add this to the manifest file:

  <receiver android:name=".AutostartService" android:enabled="true" android:exported="true"> - <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver> 

and the following permissions in the manifest file:

  <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
+1
source

Source: https://habr.com/ru/post/1436512/


All Articles