我如何让我的应用程序运行,即使应用程序被杀死?当它从最近的应用程序中删除时,它就被杀死了

koaltpgm  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(374)

我正在开发一个应用程序,可以计算一整天解锁的次数。
我见过许多类似的问题,但没有一个有效!!任何人可以帮助我,请提供上述问题的代码片段。
甚至要确保你提供的解决方案适用于androido及更高版本
主活动.java

  1. public class MainActivity extends AppCompatActivity {
  2. MyReceiver myReceiver;
  3. IntentFilter filter;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. myReceiver = new MyReceiver();
  9. filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
  10. registerReceiver(myReceiver, filter);
  11. }}

我的接收器.java

  1. public class MyReceiver extends BroadcastReceiver {
  2. private static final String TAG = "BroadCast Receiver";
  3. @Override
  4. public void onReceive(Context context, Intent intent) {
  5. if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
  6. Toast.makeText(context, "DEVICE_IS_UNLOCKED",Toast.LENGTH_LONG).show();
  7. Log.i(TAG, "Unlocked");
  8. }
  9. }
  10. }
yzxexxkh

yzxexxkh1#

在前台启动服务https://androidwave.com/foreground-service-android-example/?

jgovgodb

jgovgodb2#

你需要做后台服务。
试试下面的代码。

  1. public class BackgroundUpdateService extends Service {
  2. /**
  3. * Author:Hardik Talaviya
  4. * Date: 2019.08.3 2:30 PM
  5. * Describe:
  6. */
  7. private static final String TAG = "BackgroundLocation";
  8. private Context context;
  9. private boolean stopService = false;
  10. private Handler handler;
  11. private Runnable runnable;
  12. private NotificationCompat.Builder builder = null;
  13. private NotificationManager notificationManager;
  14. @Override
  15. public void onCreate() {
  16. Log.e(TAG, "Background Service onCreate :: ");
  17. super.onCreate();
  18. context = this;
  19. handler = new Handler();
  20. runnable = new Runnable() {
  21. @Override
  22. public void run() {
  23. try {
  24. //Add Here your code if you want start in background
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. } finally {
  28. handler.postDelayed(this, TimeUnit.SECONDS.toMillis(2));
  29. }
  30. }
  31. };
  32. if (!stopService) {
  33. handler.postDelayed(runnable, TimeUnit.SECONDS.toMillis(2));
  34. }
  35. }
  36. @Override
  37. public IBinder onBind(Intent intent) {
  38. return null;
  39. }
  40. @Override
  41. public void onTaskRemoved(Intent rootIntent) {
  42. super.onTaskRemoved(rootIntent);
  43. Log.e(TAG, "onTaskRemoved :: ");
  44. }
  45. @Override
  46. public int onStartCommand(Intent intent, int flags, int startId) {
  47. Log.e(TAG, "onStartCommand :: ");
  48. StartForeground();
  49. return START_STICKY;
  50. }
  51. @Override
  52. public void onDestroy() {
  53. super.onDestroy();
  54. Log.e(TAG, "BackgroundService onDestroy :: ");
  55. stopService = true;
  56. if (handler != null) {
  57. handler.removeCallbacks(runnable);
  58. }
  59. }
  60. /*-------- For notification ----------*/
  61. private void StartForeground() {
  62. Intent intent = new Intent(context, MainActivity.class);
  63. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  64. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
  65. String CHANNEL_ID = "channel_location";
  66. String CHANNEL_NAME = "channel_location";
  67. notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
  68. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  69. NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
  70. channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
  71. notificationManager.createNotificationChannel(channel);
  72. builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
  73. builder.setColorized(false);
  74. builder.setChannelId(CHANNEL_ID);
  75. builder.setColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
  76. builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
  77. } else {
  78. builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
  79. }
  80. builder.setOnlyAlertOnce(true);
  81. builder.setContentTitle(context.getResources().getString(R.string.app_name));
  82. builder.setContentText("Your Text");
  83. Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
  84. builder.setSound(notificationSound);
  85. builder.setAutoCancel(true);
  86. builder.setSmallIcon(R.mipmap.ic_notification_app_icon);
  87. builder.setContentIntent(pendingIntent);
  88. startForeground(101, builder.build());
  89. }
  90. }

在您的清单中添加此行

  1. <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  2. <service
  3. android:name=".BackgroundUpdateService"
  4. android:enabled="true" />

并使用下面的代码从您的活动中启动和停止服务

  1. Intent someIntent = new Intent(MainActivity.this, BackgroundUpdateService.class);
  2. startService(someIntent);//For start service
  3. stopService(someIntent); //For stop service

我希望这能帮助你!
谢谢您。

展开查看全部

相关问题