本文主要是介绍通过startService()方法使用Service,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现步骤:
1、编写类继承 Service 或其子类
2、重写onStartCommand() onBind() onCreate() onDestroy() 方法
3、在mainfest 文件中声明服务 <service android:name = ".Service" /> (Service 替换为你的服务类名)
4、在程序中启动服务,关闭服务
mService.java
package com.lanbokaka;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;public class mService extends Service {private static final String TAG = "mService";@Overridepublic void onCreate() {Log.i(TAG, "mService-->onCreate");super.onCreate();}@Overridepublic void onDestroy() {Log.i(TAG, "mService-->onDestroy");super.onDestroy();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i(TAG, "mService-->onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent arg0) {Log.i(TAG, "mService-->onBind");return null;}}
MainActivity.java
package com.lanbokaka;import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView;private Button mButton1, mButton2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mTextView = (TextView) findViewById(R.id.textView1);mButton1 = (Button) findViewById(R.id.button1);mButton2 = (Button) findViewById(R.id.button2);/* 开始服务 */mButton1.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this, mService.class);startService(intent);mTextView.setText("服务启动");}});/* 结束服务 */mButton2.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this, mService.class);stopService(intent);mTextView.setText("服务结束");}});}}
AndroidManifest.xml
<activityandroid:name="com.lanbokaka.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=".mService" ></service>
这篇关于通过startService()方法使用Service的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!