Stop Service by using Notification actionHow to check if a service is running on Android?Stop EditText from gaining focus at Activity startupstop service in androidAndroid: BatteryLevel widget not updatingService vs IntentServiceAngularJS : Initialize service with asynchronous dataUnfortunately MyApp has stopped. How can I solve this?Service close OnHandleIntent mqttApp crash when use mobie data (3g/4g)Retrofit 2 - Getting response 200, but list is empty
Other than a swing wing, what types of variable geometry have flown?
Why did NASA use Imperial units?
Reference request: mod 2 cohomology of periodic KO theory
Company requiring me to let them review research from before I was hired
Why does the salt in the oceans not sink to the bottom?
Impact of throwing away fruit waste on a peak > 3200 m above a glacier
Can't understand how static works exactly
Monty Hall Problem with a Fallible Monty
How may I shorten this shell script?
Why are angular mometum and angular velocity not necessarily parallel, but linear momentum and linear velocity are always parallel?
Who controls a summoned steed’s familiar?
Should i describe deeply a character before killing it?
I have a domain, static IP address and many devices I'd like to access outside my house. How do I route them?
Raw curve25519 public key points
Film where a boy turns into a princess
Grid/table with lots of buttons
Is it possible to eat quietly in Minecraft?
What would be the side effects on the life of a person becoming indestructible?
Can 々 stand for a duplicated kanji with a different reading?
How can I make sure my players' decisions have consequences?
Why do people say "I am broke" instead of "I am broken"?
How to extract only values greater than a threshold
Historicity doubted by Romans
What is the meaning of "you has the wind of me"?
Stop Service by using Notification action
How to check if a service is running on Android?Stop EditText from gaining focus at Activity startupstop service in androidAndroid: BatteryLevel widget not updatingService vs IntentServiceAngularJS : Initialize service with asynchronous dataUnfortunately MyApp has stopped. How can I solve this?Service close OnHandleIntent mqttApp crash when use mobie data (3g/4g)Retrofit 2 - Getting response 200, but list is empty
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm trying to build a simple application. This app is starting a service as soon as it starts which will execute a long operation (in this example I just used Thread.sleep(1000)
to simulate the operation).
However, I also need to be able to cancel the service from the foreground notification (action).
I tried a few things like jobserviceintent (I don't think it's the right approach because I need to cancel the current thread while working). I ended up using a regular service.
android manifest
<service android:name=".KotlinService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:enabled="true"
android:exported="true"/>
<receiver android:name=".KotlinReceiver">
<intent-filter>
<action android:name="com.example.myapplication.STOP_SERVICE_ACTION" />
</intent-filter>
</receiver>
KotlinService
class KotlinService : Service()
var isWorking = false
lateinit var receiever : KotlinReceiver
val FOREGROUND_NOTIFICATION = 1
val CHANNEL_ID = "CHANNEL_ID"
companion object
const val TAG = "KotlinService"
const val ACTION_BACKGROUND = "ACTION_BACKGROUND"
private const val SERVICE_ID : Int = 1000
override fun onBind(intent: Intent?): IBinder?
return null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int
var intentFilter = IntentFilter(KotlinReceiver.STOP_SERVICE_ACTION)
receiever = KotlinReceiver()
registerReceiver(receiever,intentFilter)
when(intent!!.action)
ACTION_BACKGROUND->
startForeground(FOREGROUND_NOTIFICATION,showNotification())
Log.d(TAG,"onHandleWork")
var startTime = System.currentTimeMillis()
isWorking = true
while(isWorking)
var currentTime = System.currentTimeMillis()-startTime
Log.d(TAG,"current elapsed $currentTime")
Thread.sleep(1000)
return Service.START_STICKY
private fun showNotification(): Notification
//Build your notification
val mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Testing service in background")
.setContentText("See actions below")
.setPriority(NotificationCompat.PRIORITY_LOW)
// Create Channel for Android O. DON'T FORGET
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(CHANNEL_ID,
"test",
NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
//notification stop action
var stopIntent = Intent()
stopIntent.action = KotlinReceiver.STOP_SERVICE_ACTION
var stopPendingIntent = PendingIntent.getBroadcast(this,1234,stopIntent,PendingIntent.FLAG_UPDATE_CURRENT)
var action : NotificationCompat.Action = NotificationCompat.Action.Builder(0, "Stop",stopPendingIntent).build();
mBuilder.addAction(action)
return mBuilder.build()
override fun onDestroy()
isWorking = false
unregisterReceiver(receiever)
super.onDestroy()
KotlinReceiver
class KotlinReceiver : BroadcastReceiver()
companion object
const val TAG = "KotlinReceiver"
const val STOP_SERVICE_ACTION = "com.example.myapplication.STOP_SERVICE_ACTION"
override fun onReceive(context: Context?, intent: Intent?)
var action = intent!!.action
when(action)
STOP_SERVICE_ACTION->
Log.d(TAG,"onReceive STOP_SERVICE_ACTION")
var stopIntent = Intent(context!!,KotlinService::class.java)
context!!.stopService(stopIntent)
This is how I start the service:
var intent = Intent(this,KotlinService::class.java)
intent.action = KotlinService.ACTION_BACKGROUND
startService(intent)
android kotlin service
add a comment |
I'm trying to build a simple application. This app is starting a service as soon as it starts which will execute a long operation (in this example I just used Thread.sleep(1000)
to simulate the operation).
However, I also need to be able to cancel the service from the foreground notification (action).
I tried a few things like jobserviceintent (I don't think it's the right approach because I need to cancel the current thread while working). I ended up using a regular service.
android manifest
<service android:name=".KotlinService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:enabled="true"
android:exported="true"/>
<receiver android:name=".KotlinReceiver">
<intent-filter>
<action android:name="com.example.myapplication.STOP_SERVICE_ACTION" />
</intent-filter>
</receiver>
KotlinService
class KotlinService : Service()
var isWorking = false
lateinit var receiever : KotlinReceiver
val FOREGROUND_NOTIFICATION = 1
val CHANNEL_ID = "CHANNEL_ID"
companion object
const val TAG = "KotlinService"
const val ACTION_BACKGROUND = "ACTION_BACKGROUND"
private const val SERVICE_ID : Int = 1000
override fun onBind(intent: Intent?): IBinder?
return null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int
var intentFilter = IntentFilter(KotlinReceiver.STOP_SERVICE_ACTION)
receiever = KotlinReceiver()
registerReceiver(receiever,intentFilter)
when(intent!!.action)
ACTION_BACKGROUND->
startForeground(FOREGROUND_NOTIFICATION,showNotification())
Log.d(TAG,"onHandleWork")
var startTime = System.currentTimeMillis()
isWorking = true
while(isWorking)
var currentTime = System.currentTimeMillis()-startTime
Log.d(TAG,"current elapsed $currentTime")
Thread.sleep(1000)
return Service.START_STICKY
private fun showNotification(): Notification
//Build your notification
val mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Testing service in background")
.setContentText("See actions below")
.setPriority(NotificationCompat.PRIORITY_LOW)
// Create Channel for Android O. DON'T FORGET
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(CHANNEL_ID,
"test",
NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
//notification stop action
var stopIntent = Intent()
stopIntent.action = KotlinReceiver.STOP_SERVICE_ACTION
var stopPendingIntent = PendingIntent.getBroadcast(this,1234,stopIntent,PendingIntent.FLAG_UPDATE_CURRENT)
var action : NotificationCompat.Action = NotificationCompat.Action.Builder(0, "Stop",stopPendingIntent).build();
mBuilder.addAction(action)
return mBuilder.build()
override fun onDestroy()
isWorking = false
unregisterReceiver(receiever)
super.onDestroy()
KotlinReceiver
class KotlinReceiver : BroadcastReceiver()
companion object
const val TAG = "KotlinReceiver"
const val STOP_SERVICE_ACTION = "com.example.myapplication.STOP_SERVICE_ACTION"
override fun onReceive(context: Context?, intent: Intent?)
var action = intent!!.action
when(action)
STOP_SERVICE_ACTION->
Log.d(TAG,"onReceive STOP_SERVICE_ACTION")
var stopIntent = Intent(context!!,KotlinService::class.java)
context!!.stopService(stopIntent)
This is how I start the service:
var intent = Intent(this,KotlinService::class.java)
intent.action = KotlinService.ACTION_BACKGROUND
startService(intent)
android kotlin service
add a comment |
I'm trying to build a simple application. This app is starting a service as soon as it starts which will execute a long operation (in this example I just used Thread.sleep(1000)
to simulate the operation).
However, I also need to be able to cancel the service from the foreground notification (action).
I tried a few things like jobserviceintent (I don't think it's the right approach because I need to cancel the current thread while working). I ended up using a regular service.
android manifest
<service android:name=".KotlinService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:enabled="true"
android:exported="true"/>
<receiver android:name=".KotlinReceiver">
<intent-filter>
<action android:name="com.example.myapplication.STOP_SERVICE_ACTION" />
</intent-filter>
</receiver>
KotlinService
class KotlinService : Service()
var isWorking = false
lateinit var receiever : KotlinReceiver
val FOREGROUND_NOTIFICATION = 1
val CHANNEL_ID = "CHANNEL_ID"
companion object
const val TAG = "KotlinService"
const val ACTION_BACKGROUND = "ACTION_BACKGROUND"
private const val SERVICE_ID : Int = 1000
override fun onBind(intent: Intent?): IBinder?
return null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int
var intentFilter = IntentFilter(KotlinReceiver.STOP_SERVICE_ACTION)
receiever = KotlinReceiver()
registerReceiver(receiever,intentFilter)
when(intent!!.action)
ACTION_BACKGROUND->
startForeground(FOREGROUND_NOTIFICATION,showNotification())
Log.d(TAG,"onHandleWork")
var startTime = System.currentTimeMillis()
isWorking = true
while(isWorking)
var currentTime = System.currentTimeMillis()-startTime
Log.d(TAG,"current elapsed $currentTime")
Thread.sleep(1000)
return Service.START_STICKY
private fun showNotification(): Notification
//Build your notification
val mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Testing service in background")
.setContentText("See actions below")
.setPriority(NotificationCompat.PRIORITY_LOW)
// Create Channel for Android O. DON'T FORGET
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(CHANNEL_ID,
"test",
NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
//notification stop action
var stopIntent = Intent()
stopIntent.action = KotlinReceiver.STOP_SERVICE_ACTION
var stopPendingIntent = PendingIntent.getBroadcast(this,1234,stopIntent,PendingIntent.FLAG_UPDATE_CURRENT)
var action : NotificationCompat.Action = NotificationCompat.Action.Builder(0, "Stop",stopPendingIntent).build();
mBuilder.addAction(action)
return mBuilder.build()
override fun onDestroy()
isWorking = false
unregisterReceiver(receiever)
super.onDestroy()
KotlinReceiver
class KotlinReceiver : BroadcastReceiver()
companion object
const val TAG = "KotlinReceiver"
const val STOP_SERVICE_ACTION = "com.example.myapplication.STOP_SERVICE_ACTION"
override fun onReceive(context: Context?, intent: Intent?)
var action = intent!!.action
when(action)
STOP_SERVICE_ACTION->
Log.d(TAG,"onReceive STOP_SERVICE_ACTION")
var stopIntent = Intent(context!!,KotlinService::class.java)
context!!.stopService(stopIntent)
This is how I start the service:
var intent = Intent(this,KotlinService::class.java)
intent.action = KotlinService.ACTION_BACKGROUND
startService(intent)
android kotlin service
I'm trying to build a simple application. This app is starting a service as soon as it starts which will execute a long operation (in this example I just used Thread.sleep(1000)
to simulate the operation).
However, I also need to be able to cancel the service from the foreground notification (action).
I tried a few things like jobserviceintent (I don't think it's the right approach because I need to cancel the current thread while working). I ended up using a regular service.
android manifest
<service android:name=".KotlinService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:enabled="true"
android:exported="true"/>
<receiver android:name=".KotlinReceiver">
<intent-filter>
<action android:name="com.example.myapplication.STOP_SERVICE_ACTION" />
</intent-filter>
</receiver>
KotlinService
class KotlinService : Service()
var isWorking = false
lateinit var receiever : KotlinReceiver
val FOREGROUND_NOTIFICATION = 1
val CHANNEL_ID = "CHANNEL_ID"
companion object
const val TAG = "KotlinService"
const val ACTION_BACKGROUND = "ACTION_BACKGROUND"
private const val SERVICE_ID : Int = 1000
override fun onBind(intent: Intent?): IBinder?
return null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int
var intentFilter = IntentFilter(KotlinReceiver.STOP_SERVICE_ACTION)
receiever = KotlinReceiver()
registerReceiver(receiever,intentFilter)
when(intent!!.action)
ACTION_BACKGROUND->
startForeground(FOREGROUND_NOTIFICATION,showNotification())
Log.d(TAG,"onHandleWork")
var startTime = System.currentTimeMillis()
isWorking = true
while(isWorking)
var currentTime = System.currentTimeMillis()-startTime
Log.d(TAG,"current elapsed $currentTime")
Thread.sleep(1000)
return Service.START_STICKY
private fun showNotification(): Notification
//Build your notification
val mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Testing service in background")
.setContentText("See actions below")
.setPriority(NotificationCompat.PRIORITY_LOW)
// Create Channel for Android O. DON'T FORGET
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(CHANNEL_ID,
"test",
NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
//notification stop action
var stopIntent = Intent()
stopIntent.action = KotlinReceiver.STOP_SERVICE_ACTION
var stopPendingIntent = PendingIntent.getBroadcast(this,1234,stopIntent,PendingIntent.FLAG_UPDATE_CURRENT)
var action : NotificationCompat.Action = NotificationCompat.Action.Builder(0, "Stop",stopPendingIntent).build();
mBuilder.addAction(action)
return mBuilder.build()
override fun onDestroy()
isWorking = false
unregisterReceiver(receiever)
super.onDestroy()
KotlinReceiver
class KotlinReceiver : BroadcastReceiver()
companion object
const val TAG = "KotlinReceiver"
const val STOP_SERVICE_ACTION = "com.example.myapplication.STOP_SERVICE_ACTION"
override fun onReceive(context: Context?, intent: Intent?)
var action = intent!!.action
when(action)
STOP_SERVICE_ACTION->
Log.d(TAG,"onReceive STOP_SERVICE_ACTION")
var stopIntent = Intent(context!!,KotlinService::class.java)
context!!.stopService(stopIntent)
This is how I start the service:
var intent = Intent(this,KotlinService::class.java)
intent.action = KotlinService.ACTION_BACKGROUND
startService(intent)
android kotlin service
android kotlin service
edited Mar 26 at 16:13
W0rmH0le
11.6k5 gold badges39 silver badges52 bronze badges
11.6k5 gold badges39 silver badges52 bronze badges
asked Mar 26 at 15:13
TechProTechPro
34 bronze badges
34 bronze badges
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55360532%2fstop-service-by-using-notification-action%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55360532%2fstop-service-by-using-notification-action%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown