持续在后台运行服务。例如,必须启动服务,即使应用程序关闭,也会显示20秒的Toast消息。
public class AppService extends IntentService {
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public AppService() {
super("AppService");
}
@Override
protected void onHandleIntent(Intent workIntent) {
Toast.makeText(getApplicationContext(), "hai", Toast.LENGTH_SHORT).show();
SystemClock.sleep(20000);
}
}
答案 0 :(得分:6)
下面的代码对我有用......
public class AppService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
答案 1 :(得分:2)
在您宣布服务的清单中,添加:
android:process=":processname"
这使得服务可以在一个单独的进程上运行,因此不会被应用程序杀死。
然后,您可以选择是否要使用前景。它将显示持久通知,但会降低服务被杀的可能性。
此外,如果您要创建持续投放的服务,请使用Service
,不 IntentService
。 IntentService在完成其操作后停止。
答案 2 :(得分:1)
此代码对我有用。
public class ServiceClass extends Service {
public static final int notify = 300000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
@Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Log.d("service is ","Destroyed");
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
Log.d("service is ","running");
}
});
}
}
}
答案 3 :(得分:0)
接受的答案不适用于Android 8.0(API级别26),请参见android的背景限制here
接受的答案中的修改:
1::您必须在启动服务后5秒钟内调用服务的startForeground()
方法。为此,您可以使用startForeground()
的服务方法调用onCreate()
。
public class AppService extends Service {
....
@Override
public void onCreate() {
startForeground(9999, Notification())
}
....
}
2 :您必须通过从要启动服务的位置检查API级别来调用startForegroundService()
而不是startService()
。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}