How to run a service in background forever irrespective of phone in sleep mode or running any other app?

android android-studio service

343 观看

1回复

1 作者的声誉

I want to run my service forever in the background but it stops after sometime I checked every solution on Youtube and Internet but I didn't get the answer,I tried every solution like using START_STICKY in onStartCommand() or using onTaskRemoved() method but it did not work.Any help would be appreciated.

This is my TheService class code. `

` package apphub.secretapp;

import android.app.Service;


import android.content.Intent;

import android.media.MediaPlayer;

import android.media.MediaRecorder;

import android.os.Build;

import android.os.Environment;

import android.os.IBinder;

import android.os.SystemClock;

import android.widget.Toast;

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

import java.util.Random;

/**
* Created by as on 12/24/2017.
*/

public class TheService extends Service implements 
MediaRecorder.OnInfoListener {

String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
private MediaRecorder mRecorder;
private long mStartTime;

//setting maximum file size to be recorded
private long Audio_MAX_FILE_SIZE = 1000000;//1Mb

private int[] amplitudes = new int[100];
private int i = 0;

private File mOutputFile;

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

}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent,flags,startId);
    Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
    return START_STICKY;



}



private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setOnInfoListener(this);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setMaxFileSize(Audio_MAX_FILE_SIZE);
    mRecorder.setOutputFormat
            (MediaRecorder.OutputFormat.MPEG_4);
    Toast.makeText(this, "Recording started", Toast.LENGTH_SHORT).show();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
    {
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
        mRecorder.setAudioEncodingBitRate(48000);
    } else {
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioEncodingBitRate(64000);
    }
    mRecorder.setAudioSamplingRate(16000);
    mOutputFile = getOutputFile();
    mOutputFile.getParentFile().mkdirs();
    mRecorder.setOutputFile(mOutputFile.getAbsolutePath());

    try {
        mRecorder.prepare();
        mRecorder.start();
        mStartTime = SystemClock.elapsedRealtime();
    } catch (IOException e) {
    }
}

protected void stopRecording(boolean saveFile) {
    mRecorder.stop();
    mRecorder.release();
    mRecorder = null;
    mStartTime = 0;
    if (!saveFile && mOutputFile != null) {
        mOutputFile.delete();
    }

    // to stop the service by itself


}
private File getOutputFile() {
    SimpleDateFormat dateFormat = new SimpleDateFormat
            ("yyyyMMdd_HHmmssSSS", Locale.US);
    return new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()
            + "/Voice Recorder/RECORDING_"
            + dateFormat.format(new Date())
            + ".m4a");
}



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

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


    super.onTaskRemoved(rootIntent);
}
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {

    if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
    getOutputFile();

        startRecording();



    }
}



@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    startRecording();
}

}

`

作者: Ambuj 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

32898 作者的声誉

The simple answer is: You can't! Android is an OS created for mobile devices. Mobile devices are small battery operated computers with constrained memory. With that in mind the OS will kill your service whenever it needs memory.

In further on latest versions of the OS (specially Nougat and Oreo), those limitations are being imposed more heavily to give extra battery to users.

Any tricks, hacks and work-around you find online are just that, tricks and hacks. They might work in certain conditions or certain devices for a little bit, but you still won't have your service running forever, specially not on latest Androids.

The best scenario to try to have your Service run for as much as possible is to do two things:

  1. return START_STICKY (like you're already doing). This indicates to the OS that you would like your Service to run for as long as possible, but there are zero guarantees that it will.

  2. Use a foreground service. Call the methods startForeground(int, Notification) with a notification to show on the device notification panel. This will bring your process to a foreground state and allow it to stay for a bit longer, but again, no guarantees. PS.: Remember to remove the notification on your service onDestroy.

作者: Budius 发布者: 2017 年 12 月 27 日
32x32