[英]Start Service in background Service
Is it possible to start a service from a background service? 是否可以从后台服务启动服务?
This only works when the application is open... 这仅在打开应用程序时有效...
Intent service = new Intent(this, MyForegroundSerivce.class);
service.setAction(Constants.ACTION.START_ACTION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(service);
} else {
startService(service);
}
I don't really start the service, I only call it with an action to start something, when a push notification is received. 我并没有真正启动该服务,只是在收到推送通知时通过一个操作来启动它。
Please use this service: 请使用此服务:
Start Service 启动服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(MainActivity.this, new Intent(MainActivity.this, ServiceBG.class));
} else {
startService(new Intent(MainActivity.this, ServiceBG.class));
}
Service Class 服务等级
public class ServiceBG extends Service {
private static final String NOTIFICATION_CHANNEL_ID = "my_notification";
private static final long TIME_INTERVAL = 10000;
private Handler handlerThred;
private Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setOngoing(false)
.setSmallIcon(R.drawable.ic_notification)
.setColor(getResources().getColor(R.color.white))
.setPriority(Notification.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
startForeground(1, builder.build());
}
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service", "BGS > Started");
if (handlerThred == null) {
handlerThred = new Handler();
handlerThred.post(runnableThred);
Log.w("Service ", "BGS > handlerThred Initialized");
} else {
Log.w("Service ", "BGS > handlerThred Already Initialized");
}
return START_STICKY;
}
private Runnable runnableThred = new Runnable() {
@Override
public void run() {
Log.w("Service ", "BGS >> Running");
if (handlerSendLocation != null && runnableThred != null)
handlerSendLocation.postDelayed(runnableThred, TIME_INTERVAL);
}
};
@Override
public void onDestroy() {
Log.w("Service", "BGS > Stopped");
stopSelf();
super.onDestroy();
}
}
AndroidManifest.XML AndroidManifest.xml中
<service
android:name=".ServiceBG"
android:enabled="true"
android:exported="true" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.