问题:
所以问题是我有一个应用程序,当连接WiFi(连接的SSID和其他信息)或断开连接(通过移动网络)时,它会向我们的后端发送请求.但是,随着Android 7 / N及更高版本的更改,CONNECTIVITY_CHANGE和CONNECTIVITY_ACTION不再在后台运行.现在大多数情况下人们滥用这个广播,因此我完全理解为什么要做出改变.但是,我不知道如何在当前状态下解决这个问题.
现在我不是一个AndroID开发人员(这是一个Cordova插件),所以我指望你们!
预期行为:
只要WiFi切换连接,即使应用程序被杀/在后台,应用程序也会被唤醒并发送请求.
目前的行为:
应用程序仅在应用程序位于前台时发送请求.
到目前为止尝试过:
到目前为止,我已经移动了隐藏的意图,从清单中侦听CONNECTIVITY_ACTION,并在应用程序的主要部分(插件)中手动注册它.这使得它只要应用程序在内存中就可以工作,但不能在冷启动或实际背景下工作
已经看过了:
大多数答案都谈到使用预定的工作来代替丢失的广播.我看到它是如何工作的,例如,重试下载或类似,但不适用于我的情况(但如果我错了请纠正我).以下是我已经看过的SO帖子:
Detect connectivity changes on Android 7.0 Nougat when app is in foreground
ConnectivityManager.CONNECTIVITY_ACTION deprecated
Detect Connectivity change using JobScheduler
Android O – Detect connectivity change in background
解决方法:
牛轧糖及以上:
我们必须使用JobScheduler和JobService进行连接更改.
我只能将其分为三个步骤.
Register JobScheduler insIDe activity. Also, Start JobService(
Service to handle callbacks from the JobScheduler. Requests scheduled
with the JobScheduler ultimately land on this service’s “onStartJob”
method.)
public class NetworkConnectionActivity extends AppCompatActivity { @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_network_connection); Toolbar toolbar = (Toolbar) findVIEwByID(R.ID.toolbar); setSupportActionbar(toolbar); scheduleJob(); } @RequiresAPI(API = Build.VERSION_CODES.LolliPOP) private voID scheduleJob() { JobInfo myJob = new JobInfo.Builder(0, new Componentname(this, NetworkSchedulerService.class)) .setRequiresCharging(true) .setMinimumLatency(1000) .setoverrIDeDeadline(2000) .setrequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setPersisted(true) .build(); JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDulER_SERVICE); jobScheduler.schedule(myJob); } @OverrIDe protected voID onStop() { // A service can be "started" and/or "bound". In this case, it's "started" by this Activity // and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call // to stopService() won't prevent scheduled jobs to be processed. However, failing // to call stopService() would keep it alive indefinitely. stopService(new Intent(this, NetworkSchedulerService.class)); super.onStop(); } @OverrIDe protected voID onStart() { super.onStart(); // Start service and provIDe it a way to communicate with this class. Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class); startService(startServiceIntent); }}
The service to start and finish the job.
public class NetworkSchedulerService extends JobService implements ConnectivityReceiver.ConnectivityReceiverListener { private static final String TAG = NetworkSchedulerService.class.getSimplename(); private ConnectivityReceiver mConnectivityReceiver; @OverrIDe public voID onCreate() { super.onCreate(); Log.i(TAG, "Service created"); mConnectivityReceiver = new ConnectivityReceiver(this); } /** * When the app's NetworkConnectionActivity is created, it starts this service. This is so that the * activity and this service can communicate back and forth. See "setUiCallback()" */ @OverrIDe public int onStartCommand(Intent intent, int flags, int startID) { Log.i(TAG, "onStartCommand"); return START_NOT_STICKY; } @OverrIDe public boolean onStartJob(JobParameters params) { Log.i(TAG, "onStartJob" + mConnectivityReceiver); registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION)); return true; } @OverrIDe public boolean onStopJob(JobParameters params) { Log.i(TAG, "onStopJob"); unregisterReceiver(mConnectivityReceiver); return true; } @OverrIDe public voID onNetworkConnectionChanged(boolean isConnected) { String message = isConnected ? "Good! Connected to Internet" : "Sorry! Not connected to internet"; Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); }}
Finally, The receiver class which checks the network connection
changes.
public class ConnectivityReceiver extends broadcastReceiver { private ConnectivityReceiverListener mConnectivityReceiverListener; ConnectivityReceiver(ConnectivityReceiverListener Listener) { mConnectivityReceiverListener = Listener; } @OverrIDe public voID onReceive(Context context, Intent intent) { mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context)); } public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } public interface ConnectivityReceiverListener { voID onNetworkConnectionChanged(boolean isConnected); }}
Don’t forget to add permission and service insIDe manifest file.
<?xml version="1.0" enCoding="utf-8"?><manifest xmlns:androID="http://schemas.androID.com/apk/res/androID" package="com.yourpackagename"> <uses-permission androID:name="androID.permission.INTERNET"/> <uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE"/> <!-- Always required on API < 21, needed to keep a wake lock while your job is running --> <uses-permission androID:name="androID.permission.WAKE_LOCK"/> <!-- required on API < 21 if you are using setrequiredNetworkType(int) --> <uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE"/> <!-- required on all API levels if you are using setPersisted(true) --> <uses-permission androID:name="androID.permission.RECEIVE_BOOT_COMPLETED"/> <application androID:allowBackup="true" androID:icon="@mipmap/ic_launcher" androID:label="@string/app_name" androID:roundIcon="@mipmap/ic_launcher_round" androID:supportsRtl="true" androID:theme="@style/Apptheme"> <activity androID:name=".connectivity.NetworkConnectionActivity" androID:theme="@style/Apptheme.NoActionbar"> <intent-filter> <action androID:name="androID.intent.action.MAIN"/> <category androID:name="androID.intent.category.LAUNCHER"/> </intent-filter> </activity> <!-- define your service, make sure to add the permision! --> <service androID:name=".connectivity.NetworkSchedulerService" androID:exported="true" androID:permission="androID.permission.BIND_JOB_SERVICE"/> </application></manifest>
有关更多信息,请参阅以下链接.
https://github.com/jiteshmohite/Android-Network-Connectivity
https://github.com/evant/JobSchedulerCompat
https://github.com/googlesamples/android-JobScheduler
https://medium.com/@iiro.krankka/its-time-to-kiss-goodbye-to-your-implicit-broadcastreceivers-eefafd9f4f8a
总结以上是内存溢出为你收集整理的当app被杀/在后台时,检测Android 7及更高版本中的连接变化全部内容,希望文章能够帮你解决当app被杀/在后台时,检测Android 7及更高版本中的连接变化所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)