清除最近任务时未收到广播



我想制作一个应用程序,在接收到wifi状态更改的广播时可以做一些事情。 如何以这样的方式编辑此代码,以使服务在清除最近的任务后也接收广播?请帮忙,谢谢

这是下面的代码:

public class IntentService extends Service {
SharedPreferences sharedPreferences;
SimpleDateFormat simpleDateFormat;
BroadcastReceiver broadcastReceiver= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int wifiStateExtra=intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
sharedPreferences.edit().putString(simpleDateFormat.format(new Date()),"  :"+ wifiStateExtra).apply();
Log.d("Wifi State", "  :"+wifiStateExtra +"   i :" +i);
}
};
private int i;
public IntentService() {
super();
}
@Override
public void onCreate() {
super.onCreate();
sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Toast.makeText(getApplicationContext(), "onTaskRemoved called", Toast.LENGTH_LONG).show();
startService(rootIntent);
super.onTaskRemoved(rootIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

牛轧糖及以上:我们必须使用 JobScheduler 和 JobService 进行连接更改。

我只能将其分为三个步骤。

在活动中注册作业计划程序。另外,启动作业服务(服务 以处理来自作业计划程序的回调。使用 JobScheduler 最终登陆此服务的"onStartJob"方法。

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

用于启动和完成作业的服务。

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

最后,检查网络连接的接收器类 变化。

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

不要忘记在清单文件中添加权限和服务。

<?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

简而言之:

预期行为

是你问题的一行答案。您可以尝试在 https://issuetracker.google.com/上创建问题

你会得到上面的答案。

更长的答案:

年复一年,Google在电池性能问题上限制了开发人员的许多能力。简而言之,后台没有应用程序将获得任何广播。如果您从最近版本中清除您的应用程序,它将永远停止执行,直到最终用户再次打开该应用程序。

这不仅适用于广播,也适用于背景work/tasks/jobs/alarms/任何东西。对于这些,请尝试使用工作管理器/您自己的任务/作业调度/警报管理器,一切都失败了。

为什么这一切都失败了:

Workmanager是最新的库,根据 Google 的说法,它旨在根据系统决定何时执行良好而不计成本地交付工作,以节省电池电量。正如之前的警报管理器和其他人在交付要完成的任务方面存在很多问题。

工作管理器 这也失败了,因为它有很多错误......并且正在开发中。

工作管理器真的适用于大多数设备吗?

是的,它只在模拟器上做,在市场上 98% 是中国 ROMS 修改的 android 设备,它们永远不会运行您的进程。

你应该尝试什么,哪个会起作用?

  1. 我没有看到unregister接收器在破坏。
  2. 您必须运行一个前台服务,该服务实现在 ondestroy 中注册接收器和取消注册接收器。和用户START_STICKY。
  3. 这是唯一的可能性

还有什么办法可以在那里?

使用Firebase作为框架,让谷歌处理它。它肯定会通知这样的状态,如Facebook,whatsapp,tiktok,twitter和所有其他将其用作后端,即使从最近的中删除..!!

相关内容

  • 没有找到相关文章

最新更新