Here, I will setup a class that runs a background process.
To set up the file in Eclipse, navigate to the package you want to add this to, and right click on src->"package_name", where package_name is something like com.example.project_name. From there, select New->Class. In the popup:
I set the name of my class to "Service_handler".
I set the superclass to "Service".
I then added some methods, so that the basic framework looks like this:
public class Service_handler extends ServiceAlso, add this to the xml manifest file, within the application tags.
{
public IBinder onBind(Intent intent)
{
return null;
}
public void onCreate()
{
System.out.println("onCreate");
}
public void onDestroy()
{
System.out.println("onDestroy");
}
public void onStart(Intent intent, int startid)
{
// Grab a "log_msg" from the caller
String message = intent.getStringExtra("log_msg");
System.out.println("onStart "+message);
}
}
<service android:enabled="true" android:name=".Service_handler" >
Now you start the service with code added to your main activity, like this:
public void onCreate(Bundle savedInstanceState)If you used the code above you should see this text in the logCat output, "onStart hello_from_activity".
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_first);
Intent myIntent = new Intent(getApplicationContext(),
Service_handler.class);
myIntent.putExtra("log_msg", "hello_from_activity");
startService(myIntent);
}
No comments:
Post a Comment