Learn android & lt; Service services from scratch. Forty-three. & gt;, androidservice

Source: Internet
Author: User

Learn android <Service. ..> and androidservice from scratch
In Android development, Services is an important component. If some of the operations required by some programs are time-consuming, you can define these programs in the Service, in this way, you can run the program in the background (you can also run the program without displaying the interface), that is:ServicesIn fact, it is equivalent to a non-graphic interface.ActivityProgramYou can also use Service to perform cross-process access to perform certain operations. Service is an operation component without a UI interface. Its main function is to provide necessary support for the Activity program, such as Mp3 playing software in the mobile phone, when you return to the desktop, these components can still run. In fact, these are Service functions. during development, users only need to inherit from android. app. the Service class can complete the development of the Service program, and also has its own life cycle method in the Service.
Next, we will use an example to describe the service lifecycle.

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <Button android: id =" @ + id/button1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentTop =" true "android: layout_centerHorizontal = "true" android: layout_marginTop = "90dp" android: text = "enable Service"/> <Button android: id = "@ + id/button2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignLeft = "@ + id/button1" android: layout_below = "@ + id/button1" android: layout_marginTop = "100dp" android: text = "Disable Service"/> </RelativeLayout>

Sevice
package com.example.service2;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.i("log", "onCreate");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.i("log", "onDestroy");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.i("log", "onStartCommand");return super.onStartCommand(intent, flags, startId);}}

Main class
package com.example.service2;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button button1, button2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button1 = (Button) this.findViewById(R.id.button1);button2 = (Button) this.findViewById(R.id.button2);button1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent=new Intent(MainActivity.this, MyService.class);startService(intent);}});button2.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent=new Intent(MainActivity.this, MyService.class);stopService(intent);}});}}





Bind the Service to the Activity
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <Button android: id =" @ + id/button1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignLeft = "@ + id/button2" android: layout_alignParentTop = "true" android: layout_marginTop = "22dp" android: text = "enable Service"/> <Button android: id = "@ + id/button2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignRight = "@ + id/button4" android: layout_below = "@ + id/button4" android: layout_marginTop = "32dp" android: text = "Disable Service"/> <Button android: id = "@ + id/button3" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignLeft = "@ + id/button1" android: layout_below = "@ + id/button1" android: layout_marginTop = "32dp" android: text = "binding Service"/> <Button android: id = "@ + id/button4" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_centerHorizontal = "true" android: layout_centerVertical = "true" android: text = "Unbind"/> </RelativeLayout>
Service
Package com. example. service1; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. IBinder; public class MyService extends Service {private IBinder myBinder = new Binder () {@ Override // defines the public String getInterfaceDescriptor () {System. out. println ("*** mybinder"); return "MyService Class .. ";}}; @ Overridepublic IBinder onBind (Intent intent) {System. out. println ("*** Service onBind ()"); return this. myBinder; // No processing is performed here.} @ Overridepublic void onRebind (Intent intent) {// rebind the System. out. println ("*** Service onRebind ()"); super. onRebind (intent) ;}@ Overridepublic boolean onUnbind (Intent intent) {// unbind System. out. println ("*** Service onUnbind ()"); return super. onUnbind (intent) ;}@ Overridepublic void onCreate () {// create Servicesuper. onCreate (); System. out. println ("*** Service onCreate ()") ;}@ Overridepublic void onDestroy () {// destroy servicesuper. onDestroy (); System. out. println ("*** Service onDestroy ()");} @ Overridepublic int onStartCommand (Intent intent, int flags, int startId) // run the service {System. out. println ("*** Service onStartCommand"); return Service. START_CONTINUATION_MASK; // continue execution }}

MainActivity
Package com. example. service1; import android. app. activity; import android. content. componentName; import android. content. context; import android. content. intent; import android. content. serviceConnection; import android. OS. bundle; import android. OS. IBinder; import android. OS. remoteException; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private Button button1, button2, button3, button4; // bind the service and ACtivity to private ServiceConnection serviceConnection = new ServiceConnection () {@ Overridepublic void onServiceConnected (ComponentName, IBinder service) {try {System. out. println ("### Service Connect Success. service = "+ service. getInterfaceDescriptor ();} catch (RemoteException e) {}}@ Overridepublic void onServiceDisconnected (ComponentName name) {System. out. println ("### Service Connect Failure. ") ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button1 = (Button) this. findViewById (R. id. button1); button2 = (Button) this. findViewById (R. id. button2); button3 = (Button) this. findViewById (R. id. button3); button4 = (Button) this. findViewById (R. id. button4); // start Service listening button1.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubMainActivity. this. startService (new Intent (MainActivity. this, MyService. class); onStart () ;}}); // disable the Service listener button2.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubMainActivity. this. stopService (new Intent (MainActivity. this, MyService. class); onStop () ;}}); button3.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubMainActivity. this. bindService (new Intent (MainActivity. this, MyService. class), MainActivity. this. serviceConnection, Context. BIND_AUTO_CREATE) ;}}); button4.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubMainActivity. this. unbindService (serviceConnection );}});}}


Enable



Bind


Unbind


Destroy service






Use Service to obtain other system operations
1 Public static final String CLIPBOARD_SERVICE Constant Clipboard Service
2 Public static final String WINDOW_SERVICE Constant Window Service
3 Public static final String ALARM_SERVICE Constant Alert Service
4 Public static final String AUDIO_SERVICE Constant Audio Service
5 Public static final String icationication_service Constant Notification Service
6 Public static final String SEARCH_SERVICE Constant Search Service
7 Public static final String POWER_SERVICE Constant Power Management Service
8 Public static final String WIFI_SERVICE Constant WIFI Service
9 Public static final String ACTIVITY_SERVICE Constant Running program service

Today, we will give two simple examples.
Use Service to obtain the clipboard Service
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <EditText        android:id="@+id/editText1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="41dp"        android:ems="10" >        <requestFocus />    </EditText></RelativeLayout><strong></strong>


Package com. example. service3; import android. OS. bundle; import android. app. activity; import android. content. clipboardManager; import android. view. menu; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the ClipboardManager object ClipboardManager clipboardManager = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE); // set the text clipboardManager. setText ("fengfeixue weiyang ");}}




Use service to operate mobile phone Wifi
<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayoutxmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <TextViewandroid: id = "@ + id/msg" android: layout_width = "fill_parent" android: layout_height = "wrap_content"/> <Buttonandroid: id = "@ + id/open" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "enable WIFI"/> <Buttonandroid: id = "@ + id/close" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "Disable WIFI"/> <Buttonandroid: id = "@ + id/check" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "Check WIFI status"/> </LinearLayout>

Package com. example. service5; import android. app. activity; import android. content. context; import android.net. wifi. wifiManager; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Activity {private Button open = null; // Button component private Button close = null; // Button component private Button check = null; // button component private TextView msg = null; // Text Component private WifiManager wifiManager = null; // wifi management @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); // configure the layout manager this. open = (Button) super. findViewById (R. id. open); // obtain the component this. close = (Button) super. findViewById (R. id. close); // obtain the component this. check = (Button) super. findViewById (R. id. check); // obtain the component this. msg = (TextView) super. findViewById (R. id. msg); // obtain the component this. wifiManager = (WifiManager) super. getSystemService (Context. WIFI_SERVICE); // obtain the Wife service this. open. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View view) {MainActivity. this. wifiManager. setWifiEnabled (true); // enable WifiMainActivity. this. msg. setText ("turn on WIFI, status:" + MainActivity. this. wifiManager. getWifiState (); // set text}); this. close. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View view) {MainActivity. this. wifiManager. setWifiEnabled (false); // disable WIFIMainActivity. this. msg. setText ("Disable WIFI, status:" + MainActivity. this. wifiManager. getWifiState (); // set text}); this. check. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View view) {MainActivity. this. msg. setText ("Check WIFI, status:" + MainActivity. this. wifiManager. getWifiState (); // set text }});}}





Of course, you can refer to the API below to obtain other services and configure them accordingly.

Next forecast: Notification


How can I learn android development from scratch (JAVA knows little about it)? How long can I start programming on my own?

If you want to write a basic android book while reading it, You can also read it. (In my opinion, the java basics must be good for android. If you want to learn it now, you may feel that everything in the book will work, but you will find a lot of problems. no. Compared to android, you must learn java basics first. android can learn real skills in the field. If it is better, you can make better progress in the future. Otherwise, you will not have to review the lessons of java while working like me) good method: If I don't have to write more and get more information, there will basically be a lot of online information. I generally go to forums such as eoe to ask for the basics. Most of the books are very easy to understand at the entry level (you know something about java)

Learning Android software development from scratch

Learn java basics first, and then Android Development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.