“BOOT_COMPLETED”无法正常工作。

huangapple go评论118阅读模式
英文:

BOOT_COMPLETED not worknig

问题

我想要让我的安卓应用始终在后台运行,就像 WhatsApp、Truecaller 一样。我已经尝试了所有的方法,但是当设备重新启动时,应用会停止在后台运行。为了解决这个问题,我使用了广播接收器来监听启动事件。以下是我的代码。

我的服务:

  1. public class Myservice extends Service {
  2. // 代码内容...
  3. }

广播接收器:

  1. public class Receiver extends BroadcastReceiver {
  2. // 代码内容...
  3. }

清单文件:

  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
  2. <receiver android:name=".Receiver"
  3. android:enabled="true"
  4. android:exported="true">
  5. <intent-filter>
  6. <action android:name="android.intent.action.PHONE_STATE"/>
  7. <action android:name="RestartService"/>
  8. <action android:name="android.intent.action.BOOT_COMPLETED"/>
  9. <category android:name="android.intent.category.DEFAULT"/>
  10. <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
  11. <action android:name="android.intent.action.REBOOT"/>
  12. </intent-filter>
  13. </receiver>
  14. <service android:name=".Myservice"/>

我使用的是 Android 10 和 Pie 版本,这在这些版本上能正常工作吗?

英文:

I want to run my android application always in background like whatsapp,truecaller i have used all things but when device is reboot the application is stop running in background for that i have used broadcast receiver to listen boot. here is my code.

My Service

public class Myservice extends Service {

  1. File file;
  2. private static String fileName = null;
  3. private MediaRecorder recorder = null;
  4. boolean mStartRecording = true;
  5. @Override
  6. public void onCreate() {
  7. super.onCreate();
  8. }
  9. @Override
  10. public void onDestroy() {
  11. super.onDestroy();
  12. Intent intent = new Intent(&quot;RestartService&quot;);
  13. }
  14. @RequiresApi(api = Build.VERSION_CODES.O)
  15. @Override
  16. public int onStartCommand(final Intent intent, int flags, int startId) {
  17. onTaskRemoved(intent);
  18. file = new File(Environment.getExternalStorageDirectory(), &quot;pranay&quot;);
  19. if (!file.exists()) {
  20. boolean mkdir = file.mkdirs();
  21. if (!mkdir) {
  22. Toast.makeText(this, &quot;Fialed&quot;, Toast.LENGTH_SHORT).show();
  23. }
  24. }
  25. fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + &quot;/pranay/&quot; + UUID.randomUUID().toString() + &quot;sample.mp3&quot;;
  26. Log.i(&quot;msg&quot;, &quot;running&quot;);
  27. Intent notificationIntent = new Intent(this, MainActivity.class);
  28. PendingIntent pendingIntent =
  29. PendingIntent.getActivity(this, 0, notificationIntent, 0);
  30. String channel = &quot;pranay&quot;;
  31. NotificationChannel notificationChannel = new NotificationChannel(&quot;id&quot;, channel, NotificationManager.IMPORTANCE_NONE);
  32. NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  33. manager.createNotificationChannel(notificationChannel);
  34. Notification notification = new NotificationCompat.Builder(this, &quot;id&quot;)
  35. .setContentTitle(&quot;sa&quot;)
  36. .setContentText(&quot;ssa&quot;)
  37. .setSmallIcon(R.drawable.ic_launcher_background)
  38. .setContentIntent(pendingIntent)
  39. .build();
  40. startForeground(1, notification);
  41. recorder = new MediaRecorder();
  42. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  43. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  44. recorder.setOutputFile(fileName);
  45. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  46. TelephonyManager manager1 = (TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);
  47. manager1.listen(new PhoneStateListener() {
  48. @Override
  49. public void onCallStateChanged(int state, String phoneNumber) {
  50. super.onCallStateChanged(state, phoneNumber);
  51. if (TelephonyManager.EXTRA_STATE_IDLE.equals(intent.getStringExtra(TelephonyManager.EXTRA_STATE))) {
  52. cleanup();
  53. } else if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
  54. try {
  55. recorder.prepare();
  56. } catch (IOException e) {
  57. Log.e(&quot;msg&quot;, &quot;prepare() failed&quot;);
  58. }
  59. recorder.start();
  60. mStartRecording = true;
  61. }
  62. }
  63. }, PhoneStateListener.LISTEN_CALL_STATE);
  64. return super.onStartCommand(intent,flags,startId);
  65. }
  66. private void startForeground(Notification notification, String id) {
  67. startForeground(notification, id);
  68. }
  69. private void cleanup(){
  70. if(recorder!=null)
  71. {
  72. try {
  73. recorder.stop();
  74. }catch (Exception e){
  75. Log.e(&quot;msg&quot;,String.valueOf(e.getMessage()));
  76. }finally {
  77. recorder.release();
  78. recorder=null;
  79. }
  80. stopSelf();
  81. mStartRecording = false;
  82. }
  83. }
  84. @Nullable
  85. @Override
  86. public IBinder onBind(Intent intent) {
  87. return null;
  88. }
  89. @Override
  90. public void onTaskRemoved(Intent rootIntent) {
  91. Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
  92. restartServiceIntent.setPackage(getPackageName());
  93. startService(restartServiceIntent);
  94. super.onTaskRemoved(rootIntent);
  95. }
  96. }

Broad cast receiver

  1. public class Receiver extends BroadcastReceiver {
  2. static final String ACTION = &quot;android.intent.action.BOOT_COMPLETED&quot;;
  3. @Override
  4. public void onReceive(Context context, Intent intent) {
  5. if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
  6. Toast.makeText(context,&quot;Booted&quot;,Toast.LENGTH_SHORT).show();
  7. Intent serviceIntent = new Intent(context, MainActivity.class);
  8. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  9. context.startService(serviceIntent);
  10. }
  11. }

Manifest

  1. &lt;uses-permission android:name=&quot;android.permission.RECEIVE_BOOT_COMPLETED&quot;/&gt;
  2. &lt;receiver android:name=&quot;.Receiver&quot;
  3. android:enabled=&quot;true&quot;
  4. android:exported=&quot;true&quot;
  5. &gt;
  6. &lt;intent-filter&gt;
  7. &lt;action android:name=&quot;android.intent.action.PHONE_STATE&quot;/&gt;
  8. &lt;action android:name=&quot;RestartService&quot;/&gt;
  9. &lt;action android:name=&quot;android.intent.action.BOOT_COMPLETED&quot;/&gt;
  10. &lt;category android:name=&quot;android.intent.category.DEFAULT&quot;/&gt;
  11. &lt;action android:name=&quot;android.intent.action.QUICKBOOT_POWERON&quot;/&gt;
  12. &lt;action android:name=&quot;android.intent.action.REBOOT&quot;/&gt;
  13. &lt;/intent-filter&gt;
  14. &lt;/receiver&gt;
  15. &lt;service android:name=&quot;.Myservice&quot;/&gt;

I am using android 10 and pie is it working on this versions?

答案1

得分: 1

  1. 可以使用 JobService android.intent.action.BOOT_COMPLETED但这种方法在最新版本的 Android 上不起作用
  2. ## JobService
  3. ```java
  4. public MyJobService extends JobService {
  5. private Handler myHandler = new Handler(new Handler.Callback() {
  6. @Override
  7. public boolean handler(Message msg) {
  8. Log.e("TAG", "它在重启后运行吗?");
  9. return true;
  10. }
  11. });
  12. @Override
  13. public boolean onStartJob(JobParameters params) {
  14. myHandler.sendMessage(Message.obtain(myHandler, 1, params));
  15. return true;
  16. }
  17. @Override
  18. public boolean onStopJob(JobParameters params) {
  19. myHandler.removeMessages(1);
  20. }
  21. }

MainActivity

  1. MainActivity extends AppCompatActivity {
  2. @Override
  3. protected void onCreate(@Nullable Bundle saveInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.layout);
  6. ComponentName serviceComponent = new ComponentName(this, MyJobService.class);
  7. JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
  8. builder.setMinimumLatency(1 * 1000);
  9. builder.setOverrideDeadline(5 * 1000);
  10. builder.setPersisted(true);
  11. JobScheduler jobScheduler = (JobScheduler) getSystemService(this.JOB_SCHEDULER_SERVICE);
  12. jobScheduler.schedule(builder.build());
  13. }
  14. }

AndroidManifest.xml

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. package="your.package.name">
  4. <application
  5. ..............
  6. >
  7. <service
  8. android:name=".your.package.MyJobService"
  9. android:permission="android.permission.BIND_JOB_SERVICE" />
  10. </mainfest>
英文:

You can use JobService android.intent.action.BOOT_COMPLETED this method is not worked on latest version of Android.

JobService

  1. public MyJobService extends JobService {
  2. private Handler myHandler = new Handler(new Handler.Callback() {
  3. @Override
  4. public boolean handler(Message msg) {
  5. Log.e(&quot;TAG&quot;, &quot;Does it run after reboot? &quot;);
  6. return true;
  7. }
  8. });
  9. @Override
  10. public boolean onStartJob(JobParameters params) {
  11. myHandler.sendMessage(Message.obtain(myHandler, 1, params));
  12. return true;
  13. }
  14. @Override
  15. public boolean onStopJob(JobParameters params) {
  16. myHandler.removeMessages(1);
  17. }
  18. }

MainActivity

  1. MainActivity extends AppCompatActivity {
  2. @Override
  3. protected void onCreate(@Nullable Bundle saveInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.layout);
  6. ComponentName serviceComponent = new ComponentName(this,MyJobService.class);
  7. JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
  8. builder.setMinimumLatency(1 * 1000);
  9. builder.setOverrideDeadline(5 * 1000);
  10. builder.setPersisted(true);
  11. JobScheduler jobScheduler = (JobScheduler) getSystemService(this.JOB_SCHEDULER_SERVICE);
  12. jobScheduler.schedule(builder.build());
  13. }
  14. }

AndroidManifest.xml

  1. &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  2. xmlns:tools=&quot;http://schemas.android.com/tools&quot;
  3. package=&quot;you.package.name&quot;&gt;
  4. &lt;application
  5. ..............
  6. &gt;
  7. &lt;service
  8. android:name=&quot;.your.package.MyJobService&quot;
  9. android:permission=&quot;android.permission.BIND_JOB_SERVICE&quot; /&gt;
  10. &lt;/mainfest&gt;

huangapple
  • 本文由 发表于 2020年9月18日 16:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63952408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定