无论手机处于睡眠模式还是运行任何其他应用程序,如何在后台永远运行服务?

时间:2017-12-27 16:25:37

标签: android android-studio service

我想在后台永远运行我的服务但是在我检查Youtube和Internet上的每个解决方案后它停止但是我没有得到答案,我尝试了每个解决方案,比如在onStartCommand()中使用START_STICKY或者使用onTaskRemoved()方法,但它没有工作。任何帮助将不胜感激。

这是我的TheService类代码。 `

`     包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();
}

}

`

1 个答案:

答案 0 :(得分:0)

简单的答案是:你不能! Android是为移动设备创建的操作系统。移动设备是具有受限内存的小型电池供电的计算机。考虑到这一点,操作系统将在需要内存时终止您的服务。

在最新版本的操作系统(特别是Nougat和Oreo)上,这些限制正在加大力度,为用户提供额外的电池。

你在网上找到的任何技巧,黑客和解决方法都只是那些,技巧和黑客攻击。他们可能会在某些条件或某些设备上工作一段时间,但您仍然无法让您的服务永远运行,特别是在最新的Androids上。

尝试以尽可能让您的服务运行的最佳方案是做两件事:

  1. 返回START_STICKY(就像您已经在做的那样)。这向操作系统表明您希望服务尽可能长时间运行,但没有任何保证。

  2. 使用前台服务。调用方法startForeground(int, Notification),并在设备通知面板上显示通知。这将使您的进程处于前台状态并允许它保持更长时间,但再次,无法保证。 PS。:请务必删除服务onDestroy上的通知。