简体   繁体   English

BOOT_COMPLETED 不工作

[英]BOOT_COMPLETED not worknig

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.我想始终在后台运行我的 android 应用程序,例如 whatsapp,truecaller 我已经使用了所有东西,但是当设备重新启动时,应用程序停止在后台运行,因为我使用广播接收器来监听启动。 here is my code.这是我的代码。

My Service我的服务

public class Myservice extends Service {公共类 Myservice 扩展服务 {

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("RestartService");



}

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

    onTaskRemoved(intent);

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

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

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

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


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


    Notification notification = new NotificationCompat.Builder(this, "id")
            .setContentTitle("sa")
            .setContentText("ssa")
            .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("msg", "prepare() failed");
                }

                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("msg",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 = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {

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

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

        context.startService(serviceIntent);
    }
  }

Manifest显现

   <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"/>

I am using android 10 and pie is it working on this versions?我正在使用 android 10,馅饼在这个版本上工作吗?

You can use JobService android.intent.action.BOOT_COMPLETED this method is not worked on latest version of Android.您可以使用 JobService android.intent.action.BOOT_COMPLETED 此方法不适用于最新版本的 Android。

JobService作业服务

public MyJobService extends JobService {
   private Handler myHandler = new Handler(new Handler.Callback() {
      @Override
       public boolean handler(Message msg) {
         Log.e("TAG", "Does it run after reboot? ");      
         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 AndroidManifest.xml

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM