I need to start a background service on click of android app icon.
Below is my Activity oncreate() method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_executable_runner);
startService(new Intent(this, ExeRunnerService.class));
}
And this is my overridden service class rest all is the default.
public class ExeRunnerService extends Service{
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
Thread th = new Thread(new Runnable() {
public void run() {
Log.d(TAG, "Service Running");
}
});
th.start();
}
}
I don't have any initialization code for the same.
But when I start the application I am not getting any service logs.
I would put and override on the onStartCommand, and call a super.onCreate() in the overridden onCreate method;
Like this:
public class MyService extends Service {
private static boolean isRunning = false;
private Context context;
#Override
public void onCreate() {
super.onCreate();
context = this;
}
public static boolean isServiceRunning() {
return isRunning;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!isRunning) {
isRunning = true;
}
return START_STICKY;
}
Iv added the isRunning flag because I have often experienced that my service is already running and initializing objects again then is not a good idea.
Your service is calling but problem is with thread replace your code with following code in service's on create method
public void onCreate()
{
Log.d("Run", "Service Running");
new Thread(new Runnable()
{
public void run()
{
Log.d("Run", "Service Running");
}
}).start();;
}
Related
I have a service works by pressing a button.
There's a counter that works every second inside it.
I tested it and it's working.
It also works after the application is shut down.
The problem after the application is closed
Then I'm doing a run
test the service it doesn't work.
How do I make it works after i do run from inside Android studio ?
//MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!isMyServiceRunning(SensorService.class)){
Log.i("isServiceRunning","Not");
}else {
Log.i("isServiceRunning","Don");
}
}
public void Test(View view){
startService(new Intent(this, SensorService.class));
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
/// Service
public class SensorService extends Service {
public int counter=0;
public SensorService() {
super();
Log.i("HERE", "here I am!");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
// Intent broadcastIntent = new Intent(this, SensorRestarterBroadcastReceiver.class);
stoptimertask();
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
Log.i("startTimer", "Don");
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
Log.i("initializeTimerTask", "Don");
timerTask = new TimerTask() {
public void run() {
Log.i("in_timer", "in timer ++++ "+ (counter++));
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent){
return null;
}
}
If you use "Run" from Android Studio (regardless if it's tests or the app) the service will always stop first since the whole application will always stop first. The service will not stop if you start the App manually from the device.
There is no way around this and is actually a good feature. It ensures that the App is always started cleanly on every run. If you want to share the reason of why you want to do this, there might be an alternate way of solving your problem.
I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.
I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.
I am including the simplest code i am using
ActivityClass.java
public class ActivityClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("TEST : onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lockscreen);
ButterKnife.bind(this);
}
#Override
protected void onPause() {
System.out.println("TEST : onPause");
super.onPause();
}
#Override
protected void onDestroy() {
System.out.println("TEST : onDestroy");
super.onDestroy();
}
}
Service class
public class OverlayService extends Service {
Context context;
public static final String TAG = OverlayService.class.getSimpleName();
public OverlayService(Context applicationContext) {
super();
context = applicationContext;
}
public OverlayService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "[onCreateService]");
super.onStartCommand(intent, flags, startId);
KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
if(myKM.inKeyguardRestrictedInputMode()) {
//it is locked
showOverlayActivity();
} else {
//it is not locked
}
registerOverlayReceiver();
context = this;
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterOverlayReceiver();
Log.i("EXIT", "ondestroy!");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void unregisterOverlayReceiver() {
if (overlayReceiver != null) {
unregisterReceiver(overlayReceiver);
}
}
private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";
private void registerOverlayReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(ACTION_DEBUG);
registerReceiver(overlayReceiver, filter);
}
private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "[onReceive]" + action);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
// ACTON_SCREEN_ON
showOverlayActivity();
} else if (action.equals(ACTION_DEBUG)) {
showOverlayActivity();
}
}
};
private void showOverlayActivity() {
Intent intent = new Intent();
intent.setClass(this, ActivityClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?
Well everything will be called regardless, you have defined it in your ClassName.java file.
You override the method and define it in your class to perform certain action/function when that is called.
For eg.,
You could use onResume to clear an arraylist and add updated elements to arraylist (OR) dismiss all notifications from your app on moving to that activity, say
#Override
public void onResume() {
super.onResume();
calendarList.clear();
//dismiss all notifications here
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager!=null)
notificationManager.cancelAll();
}
OR eg., onDestroy to destroy the bluetooth service,
#Override
public void onDestroy() {
super.onDestroy();
if (mBluetoothService != null) {
mBluetoothService.stop();
}
}
Hope that clarifies. Happy coding!
About service class, you should call registerReceiver() or initialize variables in onCreate instead of onStartCommand because onCreate is only called once at the first time of starting service and onStartCommand will be called every time you want to trigger an action to the service by calling startService(Intent).
I am trying to run intent service in background even if the app is closed and have written this code. But the service doesn't runs in the background.Here is my code.
MainActivity.java
package com.example.h.intentservice;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view){
Intent intent = new Intent(this,MyIntentService.class);
startService(intent);
}
public void stopService(View view){
Intent intent=new Intent(this,MyIntentService.class);
stopService(intent);
}
}
MyIntentService.java
public class MyIntentService extends IntentService {
public MyIntentService() {
super("My_Worker_Thread");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"Service started",Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"Stopped",Toast.LENGTH_LONG).show();
}
#Override
protected void onHandleIntent(Intent intent) {
synchronized (this){
int count=0;
while(count<=10)
{
try{
wait(1500);
count++;
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
First of all an intent service cannot run in the background after closing the application. An intentService is run only once and it automatically closes the thread once the task assigned to it is done. You will have to use a service for background requests.
Secondly you have not called the startService() method from the onCreate and therefore the serviceIntent has not been initiated.
In both the startService() method and the stopService() method you are passing a view which i can see is unused inside the method body. So therefore i can advice you to adjust your code this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService();
//here you have started the service intent
//if you want to stop the same just call stopService()
}
public void startService(){
Intent intent = new Intent(this,MyIntentService.class);
startService(intent);
}
public void stopService(){
Intent intent=new Intent(this,MyIntentService.class);
stopService(intent);
}
Am also posting sample code for a service that can run in the background.
Below is sample code for a service
public class UploadService extends Service {
public int counter = 0;
public UploadService(Context applicationContext) {
super();
Log.i("SERVICE", "hService started");
}
public UploadService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//instantiate your variables here
//i call my startUpload method here to doing the task assigned to it
startUpload();
return START_STICKY;
}
public void startUpload() {
//call the method with your logic here
//mine is a sample to print a log after every x seconds
initializeTimerTask();
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
// timerTask = new TimerTask() {
//we can print it on the logs as below
Log.i("in timer", "in timer ++++ " + (counter++));
//or use the print statement as below
System.out.println("Timer print " + counter++);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
}
}
I have the following code being executed, I'm running this through a debugger and audioPlayerConnection.service is always null. Why may this be?
The various log calls don't always seem to be executed either (I guess this may have to do with the service being already starte).
Intent intent = new Intent(this, AudioPlayer.class);
AudioPlayerConnection audioPlayerConnection = new AudioPlayerConnection();
startService(intent);
bindService(intent, audioPlayerConnection, Context.BIND_AUTO_CREATE);
AudioPlayerConnection
public class AudioPlayerConnection implements ServiceConnection {
public IBinder service;
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
this.service = service;
Log.d("hmm", "audio service connected!!!");
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
}
AudioPlayer
public class AudioPlayer extends Service {
public ArrayList<MediaPlayer> audioResources = new ArrayList<MediaPlayer>();
public AudioPlayer() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
Log.d("hmm", "audio service binded!!!");
return new AudioPlayerBinder();
}
public class AudioPlayerBinder extends Binder {
public void stopAll()
{
int i = 0;
for (MediaPlayer mp : audioResources)
{
mp.stop();
mp.release();
audioResources.remove(i);
i++;
}
}
public void add(Integer resourceId, boolean loop)
{
MediaPlayer mp = MediaPlayer.create(null, resourceId);
if (loop)
{
mp.setLooping(true);
audioResources.add(mp);
}
mp.start();
}
}
}
You're declaring audioPlayerService in the local scope where you are calling bindService(). The call to bindService is asynchronous, and onServiceConnected() is not being called before you are (presumably) trying to use audioPlayerConnection as if the Service was already bound.
I am using a Service to play background Music. The problem is that the music continues playing when i have finished the activity.
Here is code From Main Activity which starts the service
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
startService(svc);
BackgroundSoundService.java
public class BackgroundSoundService extends Service {
private static final String TAG = null;
public static MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("atMedia", "Backround Music playing");
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Try to stop service from your MainActivity:
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
stopService(svc);
You have to call selfStop() method inside your service.
or use stopService() API