android 46 service
service是安卓四大组建之一,service只能系统创建不能new,service也要在项目清单中注册说明,service分为2中,一种是系统级的服务,一种是我们自己写的服务。
启动和关闭service:
Activity.java
package com.sxt.day07_02; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setListener(); } private void setListener() { startServiceClickListener();//按钮事件 stopServiceClickListener();//按钮事件 } private void stopServiceClickListener() { findViewById(R.id.btnStopService).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this, MyService.class); stopService(intent); } }); } private void startServiceClickListener() { findViewById(R.id.btnStartService).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this, MyService.class); startService(intent); } }); } }
MyService.java
package com.sxt.day07_02; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService extends Service { @Override //绑定成功后回调 public IBinder onBind(Intent intent) {//绑定就是有联系,可以交换数据,可以控制你,这里只是启动Service,启动后Activity和service没有联系了,各自运行,生命周期没有关系。 return null; } @Override //Service对象创建的时候调用,只创建一次,以后再多次启动不会调用onCreate但是会调用onStartCommand,说明service同时只有一个只创建一次可以启动多次 public void onCreate() { super.onCreate(); Log.i("main","onCreate()"); } @Override //Activity启动service时候回调 public int onStartCommand(Intent intent, int flags, int startId) { Log.i("main","onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override //被系统回收的时候调用 public void onDestroy() { super.onDestroy(); Log.i("main","onDestroy()"); } }
项目描述文件加service说明:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sxt.day07_02" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.sxt.day07_02.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="com.sxt.day07_02.MyService"> service说明 </service> </application> </manifest>