運行我是新手到Android工作室和學習服務,我訪問了這個網頁:https://xjaphx.wordpress.com/2012/07/07/create-a-service-that-does-a-schedule-task/ 在這筆者做了一個後臺服務如下: 文件是這樣:如何保持後臺服務始終在後臺
所以,我創建自己的服務,稱爲TimeService:
public class TimeService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
@Override
public IBinder onBind(Intent intent) {
return 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);
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
// display toast
Toast.makeText(getApplicationContext(), getDateTime(),
Toast.LENGTH_SHORT).show();
}
});
}
private String getDateTime() {
// get date time in custom format
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
Andoid Manfest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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=".TimeService"
android:enabled="true"
android:exported="true"></service>
</application>
MainActivity.java是:
package com.example.shubhamrajput.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, TimeService.class));
}
} 我測試這個程序,我的手機上,但它不是在後臺運行,當我從應用程序托盤終止它,我想讓它永遠運行,直到用戶從設置中強制停止它,如何更改此代碼?請提供詳細的解釋並提供修改後的代碼,以便我能理解它。如何使它成爲前臺服務?
請理解,用戶非常大聲**地說**他們想要很長的電池壽命。像您這樣的服務是電池續航能力差的主要原因。這就是爲什麼Android 6.0引入打盹模式的原因,以及爲什麼Android 8.0+會限制像您的服務運行約1分鐘。我強烈建議你寫一些其他的應用程序。 「我怎樣才能使它成爲前臺服務?」 - 從服務內部調用'startForeground()'。 – CommonsWare
我知道,但不能有效地完成?因爲手機中的Gmail總是在後臺運行,並立即向我們提供最新的更新/消息,這不會導致電池耗盡? – user8517664
「但不能有效完成?」 - 每10秒輪詢一次?號碼「,因爲手機中的Gmail總是在後臺運行」 - 不,它沒有。 「並且立即爲我們提供最新的更新/消息」 - 這是因爲Google正在使用推送消息傳遞,這是普通開發人員從Firebase Cloud Messaging等服務獲得的類型。 – CommonsWare