Android 服务不在后台 运行?

Android Service not running in background?

当我按下主页按钮或后退按钮时服务运行,但当应用程序关闭时服务不在后台 运行。此外,该服务在某些(LG Nexus 5)手机中在后台运行,但在大多数手机(三星、小米)中,当应用程序关闭时,服务不是 运行。当我转到设置 > 应用程序 > 运行 时,它始终显示为应用程序 运行 并显示 1 个服务 1 个线程。我正在从 MainActivity.java

调用该服务

我希望该服务始终 运行 在后台运行,即使应用已关闭。任何帮助将不胜感激。

这是服务代码TimeService.java

public class TimeService extends Service implements
        ConnectionCallbacks, OnConnectionFailedListener {
    // constant
    public static final long NOTIFY_INTERVAL =  30 * 60 * 1000; // 30 minutes

// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;

@Override
public void onCreate() {
    // cancel if already existed
    if (mTimer != null) {
        mTimer.cancel();
    } else {
        // recreate new
        mTimer = new Timer();
    }
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

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


class TimeDisplayTimerTask extends TimerTask {


    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                // Send message in background

               sendSMS(number,msg)

                               }
                         });
                 }
             }

MainActivity.java

public class MainActivity extends Activity
{
    Button btnIn;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    btnIn = (Button) findViewById(R.id.btnIn);

    btnIn.setOnClickListener(new View.OnClickListener() {

        boolean enable = true;
        @Override
        public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, TimeService.class);
                   startService(intent);
}
}
}

Android 清单

<service android:name=".TimeService" />

如果你想让你的服务保持活跃,你应该使用前台服务。

要做到这一点,您必须运行前台服务

private void runForeground(){
//... Pending intent if you want attach it to the notification


Notification notification=new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setContentText(getString(R.string.string))
                            .setContentIntent(pendingIntent).build();

startForeground(NOTIFICATION_ID, notification);

}

NOTIFICATION_ID是一个识别号,return粘服务。

我是 运行 单独线程中的后台任务,而它应该在主线程中,这就是应用程序在某些手机中 运行 不在后台的原因。

class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {       
            // Send message in background
           sendSMS(number,msg);
             }
}