好记性不如烂笔杆-android学习笔记<十一> Service的应用

23,//Service的应用
<1>//manifest.xml对service注册
<service android:name=".FirstService"></service>
<2>//Java文件

 

 1 public class TestActivity extends Activity {
 2     private Button startServiceButton = null;
 3     private Button stopServiceButton = null;
 4     @Override
 5     public void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.main);
 8         startServiceButton = (Button)findViewById(R.id.startServiceButton);
 9         startServiceButton.setOnClickListener(new StartServiceListener());
10         stopServiceButton = (Button)findViewById(R.id.stopServiceButton);
11         stopServiceButton.setOnClickListener(new StopServiceListener());
12         System.out.println("Activity onCreate ");
13     }
14     class StartServiceListener implements OnClickListener{
15 
16         @Override
17         public void onClick(View v) {
18             Intent intent = new Intent();
19             intent.setClass(TestActivity.this,FirstService.class);
20             startService(intent);
21         }
22     }
23     class StopServiceListener implements OnClickListener{
24 
25         @Override
26         public void onClick(View v) {
27             Intent intent = new Intent();
28             intent.setClass(TestActivity.this,FirstService.class);
29             stopService(intent);
30         }
31     }
32 }

 

 

 

<3>//创建Service文件

 1 public class FirstService extends Service{
 2     @Override
 3     public IBinder onBind(Intent arg0) {
 4         System.out.println("Service onBind ");
 5         return null;
 6     }
 7     //当创建一个Service对象之后,会先调用这个函数
 8     @Override
 9     public void onCreate() {
10         super.onCreate();
11         System.out.println("Service onCreate ");
12     }
13 
14     @Override
15     public void onDestroy() {
16         super.onDestroy();
17         System.out.println("Service onDestory ");
18     }
19 
20     @Override
21     public int onStartCommand(Intent intent, int flags, int startId) {
22         System.out.println("flags--->" + flags);
23         System.out.println("startId--->" + startId);
24         System.out.println("Service onStartCommand");
25         return START_NOT_STICKY;
26     }
27     
28 }

你可能感兴趣的:(好记性不如烂笔杆-android学习笔记<十一> Service的应用)