服务的基本用法

2016-05-07  本文已影响279人  TTTqiu

一、定义服务


public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicetest"
    android:versionCode="1"
    android:versionName="1.0" >
......
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
......
        <service android:name=".MyService" >
        </service>

    </application>
</manifest>

二、启动和停止服务


1. 创建 Intent,再在活动中用 startService() 方法启动服务。
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务
2. 创建 Intent,再在活动中用 stopService() 方法停止服务。
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务

三、活动和服务进行通信


在 MyService 中:

1. 创建内部类 MyBinder 继承自 Binder,里面是活动需要调用的内容。
2. 在 MyService 中创建 MyBinder 的实例。
3. 在 onBind() 方法里返回这个实例 mBinder。
public class MyService extends Service {
    private DownloadBinder mBinder = new DownloadBinder();
    class DownloadBinder extends Binder {
        public void startDownload() {
            Log.d("MyService", "startDownload executed");
        }
        public int getProgress() {
            Log.d("MyService", "getProgress executed");
            return 0;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
.....
}

在 MainActivity 中:

1. 创建 ServiceConnection 的匿名类实例,重写 onServiceConnected() 方法和 onServiceDisconnected() 方法。
2. 在 onServiceConnected() 方法中,通过向下转型得到 MyBinder 的实例。

绑定活动和服务:

1. 创建 Intent。
2. 用 bindService() 方法绑定活动和服务。
3. 用 unbindService() 方法解除绑定。
public class MainActivity extends Activity implements OnClickListener {
    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;

    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);
        ......
        bindService = (Button) findViewById(R.id.bind_service);
        unbindService = (Button) findViewById(R.id.unbind_service);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            ......
            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;
            default:
                break;
        }
    }
}

四、服务的生命周期


  1. 调用 **startService() 方法,相应的服务就会启动起来,并回调 onStartCommand() 方法。如果这个服务之前还没有创建过onCreate() 方法会先于 onStartCommand() **方法执行。
  2. 服务启动了之后会一直保持运行状态,直到 stopService() 或 **stopSelf() **方法被调用。
  3. 还可以调用** bindService() 来获取一个服务的持久连接,这时就会回调服务中的 onBind() 方法。如果这个服务之前还没有创建过onCreate()** 方法会**先于 onBind() **方法执行。
  4. 当调用了** startService() **方法后,又去调用 stopService() 方法,这时服务中的 onDestroy() 方法就会执行,表示服务已经销毁了。
  5. 当调用了 **bindService() **方法后,又去调用 unbindService() 方法,onDestroy() 方法也会执行
  6. 需要注意的是,当对一个服务既调用了 startService() 方法又调用了 bindService() 方法一个服务只要被启动或者被绑定了之后,就会一直处于运行状态,必须要让以上两种条件同时不满足,服务才能被销毁。所以,这种情况下要同时调用 stopService() 和 unbindService() 方法onDestroy() 方法才会执行

五、服务的更多技巧


1. 使用前台服务

Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("title");
builder.setContentText("text");
builder.setWhen(System.currentTimeMillis()); // 显示时间

Intent intent=new Intent(MainActivity.this,Main2Activity.class);
PendingIntent pi=PendingIntent.getActivity(MainActivity.this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pi);

Notification notification = builder.build();

startForeground(1, notification);

使用很简单,就是把创建 Notification 方法里的 manager.notify(1, notification); 换成 startForeground(1, notification);

2. 使用 IntentService

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 处理具体的逻辑
                stopSelf();
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }
}
public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService"); // 调用父类的有参构造函数
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // 打印当前线程的id
        Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService", "onDestroy executed");
    }
}
  1. 首先要提供一个无参的构造函数,并且必须在其内部调用父类的有参构造函数。
  2. 在子类中去实现** onHandleIntent()** 这个抽象方法,这个方法已经是在子线程中运行的了。
  3. 根据 IntentService 的特性,这个服务在运行结束后应该是会自动停止的,即执行** onDestroy()** 方法。
上一篇 下一篇

猜你喜欢

热点阅读