Running Intent Service in Background - java

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();
}
}

Related

onResume() and onPause() is being called on the first launch

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).

How can I stop my service using broadcast receiver

I'm trying to stop my service with stopService(), but it will still running. It only stops when I unregister the brodcast receiver, but when I register that again, there will be two actions activated at the same time.
The thread is still running somehow, I really tried everything and reading every single post on the forum but I dind't find a solution.
Service Class
public class MyService extends Service {
final static String MY_ACTION = "MY_ACTION";
private static Context context;
private Timer timer;
public String Data;
String ok = "Database\n";
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
MyThread myThread = new MyThread();
myThread.start();
return super.onStartCommand(intent, flags, startId);
}
public class MyThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
int delay = 1000; // delay for 1 sec.
int period = 5 * 1000; // repeat every 120 sec.
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Calendar c = Calendar.getInstance();
Data = String.valueOf((c.get(Calendar.MILLISECOND)));
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED", ok);
sendBroadcast(intent);
}
}, delay, period);
} catch (Exception ex) {
ex.printStackTrace();
}
stopSelf();
}
}
}
MainActivity
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
final Intent intent = new Intent(MainActivity.this, MyService.class);
//Start our own service
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//registerReceiver(broadcastReceiver, intentFilter);
startService(intent);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//unregisterReceiver(broadcastReceiver);
stopService(intent);
}
});
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(broadcastReceiver);
super.onStop();
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int datapassed = intent.getIntExtra("DATAPASSED", 0);
String s = intent.getAction().toString();
String s1 = intent.getStringExtra("DATAPASSED");
textview.append(s1);
}
};
What I'm doing wrong is calling stopSelf() inside my Thread which is causing the service calling the onDestroy() method. I just removed that and added myTimer and myTask as local variables, then I could add myTimer.cancel() onDestroy and it worked.

How will I stop the music when I went to another activity which is CatActivity?

I am making a game app but the music still keeps playing even when I closed the game. how to stop? and how to change background music once I go to another activity after I clicked a button
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.rysk);
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() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
this is my main activity (PlayActivity.class)
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
I want to change the music when I clicked a button and went to CatActivity
You should have to work with registerReceiver,unregisterReceiver.
May this helps you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btn_startservice;
private Button btn_stopservice;
private TextView tv_servicecounter;
ServiceDemo myService;
boolean isBound;
BroadcastReceiver broadcastRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int datapassed = intent.getIntExtra("value", 0);
tv_servicecounter.setText(String.valueOf(datapassed));
}
};
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_servicecounter = (TextView) findViewById(R.id.tv_activity_main_count);
btn_startservice = (Button) findViewById(R.id.btn_activity_main_startservices);
btn_stopservice = (Button) findViewById(R.id.btn_activity_main_stopservices);
btn_startservice.setOnClickListener(
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
if (!isBound) {
bindService(objIntent, myConnection, Context.BIND_AUTO_CREATE);
isBound = true;
startService(objIntent);
} else {
isBound = false;
unbindService(myConnection);
}
}
}
);
btn_stopservice.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
if (isBound) {
isBound = false;
unbindService(myConnection);
stopService(objIntent);
} else {
stopService(objIntent);
}
}
}
);
}
#Override
protected void onResume() {
registerReceiver(broadcastRec, new IntentFilter("USER_ACTION"));
super.onResume();
}
#Override
protected void onStop() {
this.unregisterReceiver(broadcastRec);
super.onStop();
}
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
myService = ((ServiceDemo.MyLocalBinder) service).getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
if (isBound) {
unbindService(myConnection);
isBound = false;
}
}
}
And ServiceDemo.java
public class ServiceDemo extends Service {
int i;
private MyThread mythread;
public boolean isRunning = false;
Notification notification;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
mythread = new MyThread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
if (!isRunning) {
mythread.start();
isRunning = true;
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mythread.interrupt();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
public void sendBrodcastMsg(int value) {
Intent intent = new Intent();
intent.setAction("USER_ACTION");
intent.putExtra("value", value);
sendBroadcast(intent);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
class MyThread extends Thread {
static final long DELAY = 100;
#Override
public void run() {
while (isRunning) {
try {
i++;
Thread.sleep(DELAY);
sendBrodcastMsg(i);
shownotification();
} catch (InterruptedException e) {
isRunning = false;
e.printStackTrace();
}
}
stopSelf();
}
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void shownotification() {
Intent in = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), in, 0);
notification = new NotificationCompat.Builder(this)
.setContentTitle(String.valueOf(i))
.setContentText(String.valueOf(i))
.setSmallIcon(R.drawable.musicplayer)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
;
startForeground(101, notification);
}
public class MyLocalBinder extends Binder {
ServiceDemo getService() {
return ServiceDemo.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return myBinder;
}
}
put this two lines in manifest.
<service android:name=".ServiceDemo"
android:enabled="true"/>
You need to stop the player in onPause(). Following code can be used:
#Override
protected void onPause() {
super.onPause();
if (this.isFinishing()){
player.stop();
}
}
Check Android Stop Background Music for more details
for that you should stop the service in the onCreate method of the Activity. Below is the code for it :
stopService(new Intent(MyService.MY_SERVICE));
Best of Luck!
In Your MainActivity , You Should Call stopService() Inside MainActivity
#Override
public void OnPause() {
stopService(svc);
}

Android service is not starting

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();;
}

Android Background Service didn't stop/terminate

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

Categories

Resources