“BOOT_COMPLETED”无法正常工作。

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

BOOT_COMPLETED not worknig

问题

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

我的服务:

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

广播接收器:

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

清单文件:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".Receiver"
    android:enabled="true"
    android:exported="true">

    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE"/>
        <action android:name="RestartService"/>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
        <action android:name="android.intent.action.REBOOT"/>
    </intent-filter>
</receiver>
<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 {

File file;
private static String fileName = null;
private MediaRecorder recorder = null;
boolean mStartRecording = true;

@Override
public void onCreate() {
    super.onCreate();
}


@Override
public void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent(&quot;RestartService&quot;);



}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {

    onTaskRemoved(intent);

    file = new File(Environment.getExternalStorageDirectory(), &quot;pranay&quot;);
    if (!file.exists()) {
        boolean mkdir = file.mkdirs();

        if (!mkdir) {
            Toast.makeText(this, &quot;Fialed&quot;, Toast.LENGTH_SHORT).show();
        }

    }
    fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + &quot;/pranay/&quot; + UUID.randomUUID().toString() + &quot;sample.mp3&quot;;
    Log.i(&quot;msg&quot;, &quot;running&quot;);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent =
            PendingIntent.getActivity(this, 0, notificationIntent, 0);


    String channel = &quot;pranay&quot;;
    NotificationChannel notificationChannel = new NotificationChannel(&quot;id&quot;, channel, NotificationManager.IMPORTANCE_NONE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.createNotificationChannel(notificationChannel);


    Notification notification = new NotificationCompat.Builder(this, &quot;id&quot;)
            .setContentTitle(&quot;sa&quot;)
            .setContentText(&quot;ssa&quot;)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1, notification);

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setOutputFile(fileName);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    TelephonyManager manager1 = (TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);
    manager1.listen(new PhoneStateListener() {

        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            super.onCallStateChanged(state, phoneNumber);

            if (TelephonyManager.EXTRA_STATE_IDLE.equals(intent.getStringExtra(TelephonyManager.EXTRA_STATE))) {
                cleanup();
            } else if (TelephonyManager.CALL_STATE_OFFHOOK == state) {


                try {
                    recorder.prepare();
                } catch (IOException e) {
                    Log.e(&quot;msg&quot;, &quot;prepare() failed&quot;);
                }

                recorder.start();
                mStartRecording = true;
            }
        }
    }, PhoneStateListener.LISTEN_CALL_STATE);


    return super.onStartCommand(intent,flags,startId);
}

private void startForeground(Notification notification, String id) {

    startForeground(notification, id);
}
private void cleanup(){
    if(recorder!=null)
    {
        try {
            recorder.stop();
        }catch (Exception e){

            Log.e(&quot;msg&quot;,String.valueOf(e.getMessage()));
        }finally {

            recorder.release();
            recorder=null;
        }
        stopSelf();

        mStartRecording = false;

    }
}



@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
    restartServiceIntent.setPackage(getPackageName());
    startService(restartServiceIntent);
    super.onTaskRemoved(rootIntent);
}
}

Broad cast receiver

public class Receiver extends BroadcastReceiver {
static final String ACTION = &quot;android.intent.action.BOOT_COMPLETED&quot;;
@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

        Toast.makeText(context,&quot;Booted&quot;,Toast.LENGTH_SHORT).show();
        Intent serviceIntent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startService(serviceIntent);
    }
  }

Manifest

   &lt;uses-permission android:name=&quot;android.permission.RECEIVE_BOOT_COMPLETED&quot;/&gt;
   &lt;receiver android:name=&quot;.Receiver&quot;
        android:enabled=&quot;true&quot;
        android:exported=&quot;true&quot;
        &gt;

        &lt;intent-filter&gt;
            &lt;action android:name=&quot;android.intent.action.PHONE_STATE&quot;/&gt;
            &lt;action android:name=&quot;RestartService&quot;/&gt;
            &lt;action android:name=&quot;android.intent.action.BOOT_COMPLETED&quot;/&gt;
            &lt;category android:name=&quot;android.intent.category.DEFAULT&quot;/&gt;
            &lt;action android:name=&quot;android.intent.action.QUICKBOOT_POWERON&quot;/&gt;
            &lt;action android:name=&quot;android.intent.action.REBOOT&quot;/&gt;
        &lt;/intent-filter&gt;
    &lt;/receiver&gt;
    &lt;service android:name=&quot;.Myservice&quot;/&gt;

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

答案1

得分: 1

可以使用 JobService android.intent.action.BOOT_COMPLETED但这种方法在最新版本的 Android 上不起作用

## JobService

```java
public MyJobService extends JobService {
   private Handler myHandler = new Handler(new Handler.Callback() {
      @Override
       public boolean handler(Message msg) {
         Log.e("TAG", "它在重启后运行吗?");      
         return true;  
      }     
     });
@Override
public boolean onStartJob(JobParameters params) {
  myHandler.sendMessage(Message.obtain(myHandler, 1, params));
  return true; 
}
 
@Override
public boolean onStopJob(JobParameters params) {
 myHandler.removeMessages(1);  
    }   
  }

MainActivity

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

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="your.package.name">
<application
..............
 >
<service
  android:name=".your.package.MyJobService"
        android:permission="android.permission.BIND_JOB_SERVICE" />
 </mainfest>
英文:

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

JobService

public MyJobService extends JobService {
   private Handler myHandler = new Handler(new Handler.Callback() {
      @Override
       public boolean handler(Message msg) {
         Log.e(&quot;TAG&quot;, &quot;Does it run after reboot? &quot;);      
         return true;  
      }     
     });
@Override
public boolean onStartJob(JobParameters params) {
  myHandler.sendMessage(Message.obtain(myHandler, 1, params));
  return true; 
}
 
@Override
public boolean onStopJob(JobParameters params) {
 myHandler.removeMessages(1);  

    }   
  }

MainActivity

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

AndroidManifest.xml

&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
package=&quot;you.package.name&quot;&gt;
&lt;application
..............
 &gt;
&lt;service
  android:name=&quot;.your.package.MyJobService&quot;
        android:permission=&quot;android.permission.BIND_JOB_SERVICE&quot; /&gt;
 &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:

确定