-2

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
  • 11
  • 3
  • **Forever ?** Well if you find a forever solution let us all know here . Thx. – ADM Dec 27 '17 at 16:32
  • 1
    Guys instead of down voting please help me out I am a newbie to Android. – Ambuj Dec 27 '17 at 16:33
  • Read [This](https://stackoverflow.com/questions/15758980/android-service-needs-to-run-always-never-pause-or-stop) and also read about Android Api level changes Specially Android M and later . – ADM Dec 27 '17 at 16:38
  • Possible duplicate of [Android Service needs to run always (Never pause or stop)](https://stackoverflow.com/questions/15758980/android-service-needs-to-run-always-never-pause-or-stop) – Tomin B Azhakathu Dec 27 '17 at 17:09

1 Answers1

0

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
  • 39,391
  • 16
  • 102
  • 144