Java 即使应用程序已关闭,也要运行服务

Java 即使应用程序已关闭,也要运行服务,java,android,service,Java,Android,Service,我的任务是运行服务,即使应用程序已关闭 我的服务级别: 公共类MyService扩展服务{ 公共int onStartCommand(Intent Intent、int标志、int startId){ 音频经理am; am=(AudioManager)this.getSystemService(Context.AUDIO\u服务); 如果(am.getRingerMode()==AudioManager.RINGER\u模式\u正常) am.setRingerMode(AudioManager.

我的任务是运行服务,即使应用程序已关闭

我的服务级别:

公共类MyService扩展服务{
公共int onStartCommand(Intent Intent、int标志、int startId){
音频经理am;
am=(AudioManager)this.getSystemService(Context.AUDIO\u服务);
如果(am.getRingerMode()==AudioManager.RINGER\u模式\u正常)
am.setRingerMode(AudioManager.RINGER\u模式\u静音);
其他的
am.setRingerMode(AudioManager.RINGER\u模式\u正常);
分钟=新的分钟();
Calendar cal=Calendar.getInstance();
AlarmManager警报;
Intent activate=newintent(这个,MyService.class);
PendingEvent alarmIntent=PendingEvent.getService(this,0,activate,0);
alarms=(AlarmManager)this.getSystemService(Context.ALARM\u服务);
校准设置(日历小时/天,00);
校准设置(日历。分钟,分钟。分钟);
校准设置(日历秒,00);
alarms.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),alarmIntent);
Toast.makeText(这是“checkOnStart”,Toast.LENGTH_LONG.show();
return Service.START\u STICKY;
}
}
在我的活动中:

Intent activate = new Intent(this, MyService.class);
startService(activate);

但是,当我关闭应用程序并关闭服务时,我应该如何在应用程序被关闭后保持服务运行?

可以通过在服务被关闭时调用服务本身来实现。但我不能确定,因为我从来没有尝试过

这篇文章可能会有所帮助:

阅读类似的问题和答案

--编辑--

在这里,您可以从文章中获得接近完整的实现:

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorService"
            android:enabled="true" >
        </service>

        <receiver
            android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorRestarterBroadcastReceiver"
            android:enabled="true"
            android:exported="true"
            android:label="RestartServiceWhenStopped">
            <intent-filter>
                <action android:name="uk.ac.shef.oak.ActivityRecognition.RestartSensor"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
服务重启器

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        context.startService(new Intent(context, SensorService.class));;
    }
}
服务向BroadcastReceiver发送一条消息,BroadcastReceiver将在服务停止后重新启动服务(这是一个异步调用,因此不会受到服务终止的影响)


完整的源代码是

您找到解决方案了吗?我也遇到了同样的问题
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.util.Log;

    import java.util.Timer;
    import java.util.TimerTask;

    /**
     * Created by fabio on 30/01/2016.
     */
    public class SensorService extends Service {
        public int counter=0;
        public SensorService(Context applicationContext) {
            super();
            Log.i("HERE", "here I am!");
        }

        public SensorService() {
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            startTimer();
            return START_STICKY;
        }
      @Override
        public void onDestroy() {
            super.onDestroy();
            Log.i("EXIT", "ondestroy!");
            Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
            sendBroadcast(broadcastIntent);
            stoptimertask();
        }

        private Timer timer;
        private TimerTask timerTask;
        long oldTime=0;
        public void startTimer() {
            //set a new Timer
            timer = new Timer();

            //initialize the TimerTask's job
            initializeTimerTask();

            //schedule the timer, to wake up every 1 second
            timer.schedule(timerTask, 1000, 1000); //
        }

        /**
         * it sets the timer to print the counter every x seconds 
         */
        public void initializeTimerTask() {
            timerTask = new TimerTask() {
                public void run() {
                   Log.i("in timer", "in timer ++++  "+ (counter++));
                }
            };
        }

        /**
         * not needed
         */
        public void stoptimertask() {
            //stop the timer, if it's not already null
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        context.startService(new Intent(context, SensorService.class));;
    }
}