I've got a service:
public class FileObserverService extends Service {
private FileObserverForNewFirFiles fObs;
#Override
public void onCreate() {
Log.i("FILE_OBSERVER_SERVICE: ", "INSIDE ONCREATE()");
File f = new File("/mnt/sdcard/Bluetooth");
createFileObserver(f);
}
public void createFileObserver(File f) {
if(!f.isDirectory()) {
Log.i("FILEOBSERVER: ", "FILE NOT A DIRECTORY!");
}
else {
fObs = new FileObserverForNewFirFiles(f.getAbsolutePath());
}
}
#Override
public void onStart(Intent i, int startid) {
fObs.startWatching();
Toast.makeText(this.getApplicationContext(), "start monitoring file modification", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
fObs.stopWatching();
Toast.makeText(this.getApplicationContext(), "stop monitoring file modification", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
From my Main Activity, I call this class this way:
startService(new Intent(ThisClass.this, FileObserverService.class));
I thought that the onCreate method would print out something to the LogCat, referring to the first line of this method. But it doesnt seems to do it. Any hit?
I think what you really want is an IntentService
http://developer.android.com/reference/android/app/IntentService.html
just replace your method signature of onCreate
with onStartCommand
Basically you haven't done everything you need to do to get a regular old service going and IntentService will do all that work without any more effort from yourself.
Related
I have created a service and called this service class from BaseActivity.
Intent serviceIntent = new Intent(this, UserAvailabilityService.class);
startService(serviceIntent);
public class UserAvailabilityService extends Service {
private static final String TAG = UserAvailabilityService.class.getSimpleName();
boolean isChecked = false;
boolean isUserAvailable = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
isChecked = getAvailableStatusFromFref();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()");
return START_NOT_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(TAG, "onTaskRemoved()");
if(isChecked) {
//Hit a api
}
else
{
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "onLowMemory()");
}
}
If app crashes or closed from task manager then that time i want to hit api.
Right Now, When i am swipping the app from background this onTaskRemoved method is calling. and i am hitting the api.
But when i am closing the same app from task manager (Setting->Apps->App name->Force Stop) then this onTaskRemoved method is not calling.
Any idea,please let me know.
Not possible. You cannot tell from within an app whether the app will be terminated. You could watch for termination from a second app, but at any time the first can be closed without notice. Not to mention the variety of ways that both apps could be shut down (for example, they could just pull the battery). You should never write code that requires you to do something on shutdown, because it will never be reliable.
The best you can do is calling isFinishing() which checks if it is being destroyed from you onPause() method
#Override
protected void onPause(){
super.onPause();
if(isFinishing){
callApi();
}
}
I'm using the below code to start a service. this service should start Async task that checks mysql and provide notifications. the service isn't starting and I can't find why? I receive no Log from the service.
(when I call the Async task from main activity directly without service it works fine).
Main Activity code:
Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
MainActivity.this.startService(startIntent);
Service Class Code:
public class ForegroundService extends Service {
private static final String LOG_TAG = "ForegroundService";
#Override
public void onCreate() {
Log.i(LOG_TAG, "On Create");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "On Start");
new Thread(new Runnable() {
#Override
public void run() {
String newoperator = "Go";
TimeSync ReportCheck= new TimeSync(getApplicationContext());
ReportCheck.execute(newoperator);
}
}).start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I also found some solutions adding the below command in main activity but the command isn't applicable in my android studio.
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
What version of android studio do you use? Have you tried to updated to the latest version?
Download Android Studio 2.1
I have a service that has various methods and all they do is give a logcat message but these methods doesn't seem to be called even though I have created a instance of that service in my activity class.
My service class code is-
public class service extends Service {
IBinder ob=new My_Ibinder();
public class My_Ibinder extends Binder{
public service get_MyService(){
return service.this;
}
}
#Override
public void onCreate() {
super.onCreate();
Log.e("SERVICE CREATED","");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("SERVICE OnStartCommand","");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.e("SERVICE onBind","");
return ob;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("SERVICE DESTROYED","");
}
String data(){
Log.e("SERVICE data method","");
return "DATA SUCCESSFULLY TRANSFERRED";
}
public void ok(){
Log.e("SERVICE ok method","");
}
}
Here the methods I call are data() and ok().My activity class is-
Button start,stop,data,check;
TextView tv;
service ser;
Boolean flag=false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.start);
check=(Button)findViewById(R.id.check);
stop=(Button)findViewById(R.id.stop);
data=(Button)findViewById(R.id.data);
tv=(TextView)findViewById(R.id.tv);
start.setOnClickListener(new OnClickListener(){public void onClick(View v){ bindService(new Intent(MainActivity.this,service.class),sc,Context.BIND_AUTO_CREATE); }});
stop.setOnClickListener(new OnClickListener(){public void onClick(View v){ unbindService(sc); flag=false; }});
data.setOnClickListener(new OnClickListener(){public void onClick(View v){ ser.ok();tv.setText(ser.data()); }});
check.setOnClickListener(new OnClickListener(){public void onClick(View v){ Log.e(""+flag,"sfsfsdfdssfsdffsdfs"); }});
}
private ServiceConnection sc=new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
My_Ibinder ob=(My_Ibinder)service;
ser=ob.get_MyService();
flag=true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
flag=false;
ser=null;
}
};
On clicking the button I don't get any logcat message. Neither from the methods I need to call, nor from the onCreate(),onBind() and onDestroy() methods which should have been called if the service is successfully created.
I've checked running processes in settings and this service doesn't exist over there.Strangely, if I start the service with startService(intent) then it seems to work fine(although I'm not able to communicate with it). I guess there is some problem with Binding the service.
Kindly Help.
Finally got it... Such a silly silly mistake I've done. While giving logcat message I didn't added a text attribute to it and it just had a tag. Now that I've added a text to it, it works perfectly. Such a small yet important point to be noted. Certainly we all use logcat messages to DEBUG our program but this time the PROBLEM was LOGCAT itself. Never gonna forget this one !!!
Refer http://developer.android.com/guide/components/aidl.html to communicate service from activity.
For a demo I print a Toast after Evert 10 sec. using Service class.
It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.
But I want to that toast either I'll kill the App or back press Here is code snippet :
ServiceDemo.java
public class ServiceDemo extends Activity {
private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {
#Override
public void run() {
as();
myHandler.postDelayed(this, 10000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
myHandler.postDelayed(drawRunnable, 10000);
startService(new Intent(this, MyService.class));
}
public void as(){
startService(new Intent(this, MyService.class));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Service.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}
Edit 1
moveTaskToBack(true);
I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, Service not responding
I think you need to override onStartCommand instead of onStart()
like:
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
i think AlarmManager is what you want.
You have to user AlarmManager, here's an example : Alarm Manager Example
Your task will be executed even if the application is terminated.
But if the application is killed by the user, the Alarm will be canceled. See this discussion How to create a persistent AlarmManager
Actually i have to perform some technique in which some particular method will be called after specified time until app destroyed.I Google it and have found services.Using services this work can be performed.I have gone through many Service tutorials so now i can work with services but can anybody tell me how to do this. Should i use services for call particular tack in the background of the activity after specified time?...Thanks....
Edit: I have used following code
public class MyService extends Service {
int count = 0;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
Toast.makeText(this, "Service started................",
Toast.LENGTH_SHORT).show();
}
private Runnable updateTimeTask = new Runnable() {
public void run() {
if (count == 50) {
count = 0;
Tocken_parser tocken = new Tocken_parser();
tocken.tockenParser("1");
Toast.makeText(MyService.this, "coutn===", Toast.LENGTH_SHORT)
.show();
System.out.println("Count ===============");
}
count++;
handler.postDelayed(this, 1000);
}
};
private Handler handler = new Handler();
#Override
public void onDestroy() {
super.onDestroy();
System.out
.println("Service destroyed........................................");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Its working properly but tell me one thing, how to stop services when activity destroyed.
The answer is YES. Also, the Service that spawned by Activity will be destroyed together; unless, you assign a schedule check on Alarm to wake up your dead Service.