class ForegroundService : Service() {
private val CHANNEL_ID = "1"
companion object {
fun startService(context: Context, message: String) {
val startIntent = Intent(context, ForegroundService::class.java)
startIntent.putExtra("inputExtra", message)
ContextCompat.startForegroundService(context, startIntent)
}
fun stopService(context: Context) {
val stopIntent = Intent(context, ForegroundService::class.java)
context.stopService(stopIntent)
}
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//do heavy work on a background thread
val input = intent?.getStringExtra("inputExtra")
createNotificationChannel()
val notificationIntent = Intent(this, PostingVKActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE
)
/*
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service Kotlin Example")
.setContentText(input)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
*/
//stopSelf();
return START_NOT_STICKY
}
override fun onBind(intent: Intent): IBinder? {
return null
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(CHANNEL_ID, "1",
NotificationManager.IMPORTANCE_DEFAULT)
val manager = getSystemService(NotificationManager::class.java)
manager!!.createNotificationChannel(serviceChannel)
// }
}
}
class ForegroundService2 : Service() {
override fun onCreate() {
super.onCreate()
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val input = intent.getStringExtra("inputExtra")
createNotificationChannel()
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE
)
val notification: Notification = Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.alert_light_frame)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
}
@Nullable
override fun onBind(intent: Intent): IBinder? {
return null
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
Companion.CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(
NotificationManager::class.java
)
manager.createNotificationChannel(serviceChannel)
}
}
companion object {
const val CHANNEL_ID = "ForegroundServiceChannel"
}
}
@IBAction func button(_ sender: UIButton) {
acrivityIndicator.startAnimating() //чтобы выполнилось в первую очередь
// остальной код с URLSession
}
/*START DELETE Black List*/
var b: Int = 0
while(b<self.blackList.count){
if(b > 0){
OperationQueue.main.addOperation {
self.dismiss(animated: true, completion: nil)
}
}
let vkUrl = URL(string: "http://url.ru/test/deleteBlackList.php")
var request = URLRequest(url: vkUrl!)
let device: String = "\(shared.nameDevice)"
let postString = "v=5.80&lang=ru&https=1&device=\(device)&access_token=\(self.access_token)&owner_id=\(self.blackList[b].id)"
request.httpBody = postString.data(using: String.Encoding.utf8);
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.addValue(shared.userAgent, forHTTPHeaderField: "User-Agent")
request.addValue("300", forHTTPHeaderField: "content-Length")
request.addValue("1", forHTTPHeaderField: "X-Get-Processing-Time")
request.addValue("remixlang=0", forHTTPHeaderField: "Cookie")
URLSession.shared.dataTask(with: request) {(data, response, error) in
guard let data = data else {
let error_code = String(error!._code)
let error_msg = "DeleteFromBlackList 1. Ошибка соединения с сервером. Пожалуйста, попробуйте позже. \n Если ошибка будет повторяться, то сообщите в службу поддержки приложения. \n Код ошибки: " + error_code"
let alertVC = UIAlertController(title: "Ошибка", message: error_msg, preferredStyle: .alert)
let actionOK = UIAlertAction(title: "OK", style: .default, handler: nil)
alertVC.addAction(actionOK)
DispatchQueue.main.async(execute: {
self.present(alertVC, animated: true, completion: nil)
})
return
}
do {
self.json = data
self.k = true
}
}.resume()
/*WAIT RESPONSE*/
var i = 0
while (self.k != true && i<20){
sleep(1)
i += 1
}
self.k = false
if i >= 20 {
let error_msg = "Время ожидания ответа от сервера приложения истекло, проверьте интернет-соединение. Если ошибка будет повторяться много раз, то напишите в поддержку приложения. \n Попытка получить черный список."
let alertVC = UIAlertController(title: "Ошибка", message: error_msg, preferredStyle: .alert)
let actionOK = UIAlertAction(title: "OK", style: .default, handler: nil)
alertVC.addAction(actionOK)
DispatchQueue.main.async(execute: {
self.present(alertVC, animated: true, completion: nil)
})
return
}
/*END WAIT RESPONSE*/
/*JSON DECODE*/
var dataString: String = ""
dataString = NSString(data: self.json!, encoding: String.Encoding.utf8.rawValue)! as String
print("------------------")
print(dataString)
OperationQueue.main.addOperation {
let alert = UIAlertController(title: "Удалено: \(b)", message: nil, preferredStyle: .alert)
let activityIndicator = UIActivityIndicatorView(style: .medium)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.isUserInteractionEnabled = false
activityIndicator.startAnimating()
alert.view.addSubview(activityIndicator)
alert.view.heightAnchor.constraint(equalToConstant: 95).isActive = true
activityIndicator.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor, constant: 0).isActive = true
activityIndicator.bottomAnchor.constraint(equalTo: alert.view.bottomAnchor, constant: -20).isActive = true
self.present(alert, animated: true)
}
b += 1
}//END WHILE
OperationQueue.main.addOperation {
self.dismiss(animated: true, completion: nil)
}
}//END Global
/*END DELETE Black List*/
Есть функция, которой надо работать в фоновом режиме:
в Активити через кнопку запускать?