MainActivity
1 ackage com.example.zhangmeng.servicedemo; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 8 public class MainActivity extends AppCompatActivity { 9 private Intent intent; 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 intent=new Intent(MainActivity.this,MyService.class); 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 17 findViewById(R.id.button_StartService).setOnClickListener(new View.OnClickListener() { 18 @Override 19 public void onClick(View v) { 20 startService(intent); 21 22 } 23 }); 24 25 findViewById(R.id.button_StopService).setOnClickListener(new View.OnClickListener() { 26 @Override 27 public void onClick(View v) { 28 stopService(intent); 29 } 30 }); 31 32 33 } 34 }
Service代码如下,一个程序中只可能有一个service
1 package com.example.zhangmeng.servicedemo; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 import android.provider.Settings; 7 8 public class MyService extends Service { 9 public MyService() { 10 } 11 12 @Override 13 public IBinder onBind(Intent intent) { 14 // TODO: Return the communication channel to the service. 15 throw new UnsupportedOperationException("Not yet implemented"); 16 } 17 18 @Override 19 public int onStartCommand(Intent intent, int flags, int startId) { 20 new Thread(){ 21 @Override 22 public void run() { 23 super.run(); 24 while (true) 25 { 26 System.out.println("The service is running!"); 27 try { 28 sleep(1000); 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 } 33 } 34 }.start(); 35 return super.onStartCommand(intent, flags, startId); 36 } 37 }
MainActivity的xml文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 android:orientation="vertical" 11 tools:context="com.example.zhangmeng.servicedemo.MainActivity"> 12 13 14 <Button 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" 17 android:text="启动服务" 18 android:id="@+id/button_StartService" /> 19 20 <Button 21 android:layout_width="wrap_content" 22 android:layout_height="wrap_content" 23 android:text="停止服务" 24 android:id="@+id/button_StopService" /> 25 26 </LinearLayout>