【发布时间】:2017-03-07 11:21:06
【问题描述】:
这是我想在后台运行的服务
public class CustomMyService extends Service {
public CustomMyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);
}
}
清单文件
<service android:name=".CustomMyService">
<intent-filter android:priority="1000">
<action android:name="android.location.PROVIDERS_CHANGED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
请有人告诉我。我做了所有的谷歌和 youtube 搜索,没有任何工作。
我正在使用 redmi note 3,其中我有一个名为 autostart 的选项,如果我允许此应用程序自动启动,则服务将在后台运行。
但是很多其他安卓智能手机都没有这个选项,所以当应用终止时,应用服务会被杀死。
请让我知道服务如何运行,即使在应用程序终止后也是如此。
【问题讨论】:
-
使用您希望服务执行的代码编写一个私有类方法,并从
onStartCommand()调用它。除非您需要一些东西来初始化服务,否则不需要构造函数。