标签:
一.特点
(1)没有用户界面,在后台运行;
(2)应用退出后,Service还继续运行;
(3)默认情况下,在应用的主线程运行;
(4)应用重新启动,可以继续调用前面启动的Service;
二.分类
(1)本地服务
①Service对象和启动者在同一个进程内
②进程内通信
(2)远程服务
①Service对象和启动者在不同的进程内
②进程间通信:通过AIDL(Android接口定义语言)来实现
三.实现
(1)普通方式
(2)绑定方式
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 tools:context="com.hanqi.testservice.MainActivity" 11 android:orientation="vertical"> 12 13 <Button 14 android:layout_width="match_parent" 15 android:layout_height="wrap_content" 16 android:text="普通方式启动" 17 android:onClick="bt1_OnClick"/> 18 <Button 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content" 21 android:text="普通方式停止" 22 android:onClick="bt2_OnClick"/> 23 </LinearLayout>
1 package com.hanqi.testservice; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Toast; 8 9 public class MainActivity extends AppCompatActivity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 } 16 17 //普通方式启动 18 public void bt1_OnClick(View v) 19 { 20 //准备Intent:显示意图 21 Intent intent = new Intent(this,MyService.class); 22 23 //启动MyService 24 startService(intent); 25 26 Toast.makeText(MainActivity.this, "MyService已启动", Toast.LENGTH_SHORT).show(); 27 } 28 29 //普通方式停止 30 public void bt2_OnClick(View v) 31 { 32 //准备Intent:显示意图 33 Intent intent = new Intent(this,MyService.class); 34 35 //启动MyService 36 stopService(intent); 37 38 Toast.makeText(MainActivity.this, "MyService已停止", Toast.LENGTH_SHORT).show(); 39 } 40 }
1 package com.hanqi.testservice; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 import android.util.Log; 7 8 public class MyService extends Service { 9 public MyService() { 10 11 Log.e("TSG","MyService被构造"); 12 } 13 14 //回调方法 15 //绑定 16 @Override 17 public IBinder onBind(Intent intent) { 18 // TODO: Return the communication channel to the service. 19 throw new UnsupportedOperationException("Not yet implemented"); 20 } 21 }
标签:
原文地址:http://www.cnblogs.com/cycanfly/p/5595085.html