Android的Service服务的基本的介绍

来源:互联网 发布:centos yum nginx 编辑:程序博客网 时间:2024/06/03 14:33

1、Service是Android后台进行,我们在Activity中可以启动Service服务

一般服务类需要继承Service

需要重写几个方法如onCreate() onStartCommand() onDestroy()  onBind()

当我们在MainActivity中主要使用的是startService(Intent  intent)启动服务

即Intent intent=new Intent();

intent.setClass(MainActivity.this,MyService.class);

startService(intent);

接着就会执行MyService类中的方法 如果该服务还没有被创建就会调用onCreate()

然后调用onStartCommand()方法,主要的业务逻辑卸载该方法中。

在MainActivity中停止服务主要使用

Intent intent=new  Intent();

intent。setClass(MainActivoity.this,MyService.class);

stopService(intent);

就会调用MyService中的onDestroy()方法。


2、为了让Activity和Service可以进行充分的交互,Activity可以调用Service中指定的任意方法,需要

将Activity和Service进行绑定

在Activity中需要定义Service中自定义的Binder对象,通过ServiceConnection类获取Service中返回的Binder对象,进而调用Service中Binder类中的方法。

binderService(Intent ,ServiceConnection,常量)

unBinderService(Intent)

3、每一个服务函数结束,并不会主动的结束该Service

为了方法,Android提出了IntentService

当我们启动这个Service的时候,当我们的业务逻辑执行完毕的时候,程序自动执行onDestroy()方法

以下是关于上面三点的例子:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" />


    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />


    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service" />


    <Button
        android:id="@+id/unbind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind Service" />


    <Button
        android:id="@+id/start_intent_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start IntentService" />


</LinearLayout>



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicetest"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.servicetest.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=".MyService" >
        </service>
        <service android:name=".MyIntentService"></service>
    </application>


</manifest>



package com.example.servicetest;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {


private Button startService;


private Button stopService;


private Button bindService;


private Button unbindService;


private Button startIntentService;


private MyService.DownloadBinder downloadBinder;


private ServiceConnection connection = new ServiceConnection() {


@Override
public void onServiceDisconnected(ComponentName name) {
}


@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start_service);
stopService = (Button) findViewById(R.id.stop_service);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
startIntentService = (Button) findViewById(R.id.start_intent_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
startIntentService.setOnClickListener(this);
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
case R.id.start_intent_service:
Log.d("MainActivity", "Thread id is " + Thread.currentThread().getId());
Intent intentService = new Intent(this, MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}


}


package com.example.servicetest;


import android.app.IntentService;
import android.content.Intent;
import android.util.Log;




/*
 * 通过使用IntentService 可以创建一个新的线程去执行相应的任务,并且在任务执行完毕的时候,自动调用destroy
 * 
 * */
public class MyIntentService extends IntentService {


public MyIntentService() {
super("MyIntentService");
}


@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
}


@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}


}



package com.example.servicetest;


import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;


public class MyService extends Service {


private DownloadBinder mBinder = new DownloadBinder();


class DownloadBinder extends Binder {


public void startDownload() {
new Thread(new Runnable() {
@Override
public void run() {
// start downloading
}
}).start();
Log.d("MyService", "startDownload executed");
}


public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}


}


@Override
public IBinder onBind(Intent intent) {
Log.d("MyService", "onBind executed");
return mBinder;
}


@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,
"Notification comes", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, "This is title", "This is content",
pendingIntent);
startForeground(1, notification);
Log.d("MyService", "onCreate executed");
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
new Thread(new Runnable() {  
       @Override  
       public void run() {  
           // do something here
       }  
   }).start();
return super.onStartCommand(intent, flags, startId);
}


@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}


}

0 0