Reputation: 1424
I have a services can be called by other activities and threads and some receivers wait for the callback from it. I know that a service is only one instance in my app. I want to run the service when it needs to be called, not all the time hanging on in the background. How can I start/stop the service safely? Thanks in advance.
Upvotes: 1
Views: 1216
Reputation: 2714
Use IntentService.
Its very much like your needs. It starts when you want it to be...and stop when it got done its tasks automatically. So frees its memory immediately. Another big advantage is that it runs in its own thread, hence your main thread/UI will never halt.
If you decide that this answers your question, please mark it as "accepted". This will raise both your and my reputation score.
Upvotes: 4
Reputation: 6108
MainPage.java
package com.pack.service_tost_handler;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainPage extends Activity {
static Mhandler mhandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
mhandler=new Mhandler();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Intent i = new Intent(MainPage.this, ServicePage.class);
Log.i("log", "i m create in main page");
startService(i);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_page, menu);
return true;
}
class Mhandler extends Handler
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==111)
{
Toast.makeText(MainPage.this, "welcome to "+ msg.obj.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
ServicePage.java
package com.pack.service_tost_handler;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ServicePage extends Service implements Runnable
{
String[] ary;
@Override
public void onCreate()
{
Log.i("log", "create");
super.onCreate();
ary= new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t1 = new Thread(this);
t1.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null; }
@Override
public void run() {
for(int i=0;i<ary.length;i++)
{
try
{
synchronized (this) {
this.wait(5000);
}
}
catch (Exception e) {
Log.i("log", "Exception");
}
Message msg= MainPage.mhandler.obtainMessage(111);
msg.obj=ary[i];
MainPage.mhandler.sendMessage(msg);
}
}
}
Upvotes: 2