Service(服务)

来源:互联网 发布:埃文蕾切尔伍德 知乎 编辑:程序博客网 时间:2024/04/28 12:44

使用startService()启动Service

...@Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.start_server:            Intent startIntent = new Intent(this,MyService.class);            startService(startIntent);            break;        case R.id.stop_server:            Intent stopIntent = new Intent(this,MyService.class);            stopService(stopIntent);            break;        default:            break;        }    }

MyService.java

package com.example.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service{    static final String TAG = "MyService";    @Override    public IBinder onBind(Intent arg0) {        Log.v(TAG, "onBind");        return null;    }    @Override    public void onCreate() {        super.onCreate();        Log.v(TAG, "onCreate");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.v(TAG, "onStartCommand");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        Log.v(TAG, "onDestroy");    }}

在AndroidManifest.xml注册Service

 <service android:name="com.example.service.MyService">        </service>

startService();
1.如果服务没启动,则调用onCreate(),onStartCommand();
2.如果服务以及启动,只会调用onStartCommand();

stopService();
调用onDestory();

<——————————->

使用bindService();

MyService.java

public class MyService extends Service{    static final String TAG = "MyService";    DownloadBinder downloadBinder = new DownloadBinder();     public class DownloadBinder extends Binder{        public void download(){            Log.v(TAG, "download");        }        public int getProgress(){            Log.v(TAG, "getProgress");            return 0;        }    }    @Override    public IBinder onBind(Intent arg0) {        Log.v(TAG, "onBind");        return downloadBinder;    }    @Override    public void onCreate() {        super.onCreate();        Log.v(TAG, "onCreate");    }    @Override    public void onDestroy() {        super.onDestroy();        Log.v(TAG, "onDestroy");    }}

Mainactivity.java

//全局变量private MyService.DownloadBinder downloadBinder;    private ServiceConnection serviceConnection = new ServiceConnection() {        @Override        public void onServiceDisconnected(ComponentName arg0) {            // TODO Auto-generated method stub        }        @Override        public void onServiceConnected(ComponentName arg0, IBinder service) {            downloadBinder = (DownloadBinder) service;            downloadBinder.download();            downloadBinder.getProgress();        }    };...{    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.start_server:            Intent bindIntent = new Intent(this,MyService.class);            bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);            break;        case R.id.stop_server:            unbindService(serviceConnection);            break;        default:            break;        }    }}

当调用bindService();
先后调用,onCreate(),onBind(),download(),getProgress()。

当调用unbindService();
调用onDestroy();

当程序同时调用了startService()和bindService()
要服务销毁必须要调用stopService()和unbindService(),只有这样onDestory()才会被执行

调用前台服务(不会因为内存不够而被回收)

@Override        public void onCreate() {            super.onCreate();            Log.v(TAG, "onCreate");            Notification notification = new Notification(R.drawable.ic_launcher,"前台服务",System.currentTimeMillis());            Intent notificationIntent = new Intent(this,MainActivity.class);            PendingIntent pi = PendingIntent.getActivity(this,0, notificationIntent,0);            notification.setLatestEventInfo(this, "title", "content",pi);            startForeground(1, notification);        }

效果
这里写图片描述

IntentService(里面定义好了一次子线程的耗时操作函数)

MyIntentService.java

package com.example.service;import android.app.IntentService;import android.content.Intent;import android.util.Log;public class MyIntentService extends IntentService{    static final String TAG = "MyIntentService";    //调用无参的构造函数    public MyIntentService() {        super("MyIntentService");        Log.v(TAG,"MyIntentService");    }    @Override    protected void onHandleIntent(Intent arg0) {        Log.v(TAG,"onHandleIntent :"+Thread.currentThread().getId());    }    @Override    public void onDestroy() {        super.onDestroy();        Log.v(TAG,"onDestory");    }}

MainActivity.java

...public void onClick(View v) {        switch (v.getId()) {        case R.id.start_server:            Intent intent = new Intent(this,MyIntentService.class);            startService(intent);            break;        default:            break;        }

效果:
这里写图片描述

定时服务(例子)
使用alarm

MainActivity.java

public void onClick(View v) {        switch (v.getId()) {        case R.id.start_server:            Intent intent = new Intent(this,MyService.class);            startService(intent);            break;        default:            break;        }

MyService.java

package com.example.service;import com.example.broadcastReceiver.AlarmReceiver;import android.app.AlarmManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import android.text.format.Time;import android.util.Log;public class MyService extends Service{    @Override    public IBinder onBind(Intent arg0) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate() {        super.onCreate();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Time time=new Time("GMT+8");        time.setToNow();        Log.v("service", time.hour+":"+time.minute+":"+time.second);        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);        long triggerAtTime = SystemClock.elapsedRealtime()+10*1000;        //每隔10秒打印一次        Intent i = new Intent(this,AlarmReceiver.class);        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();    }}

AlarmReceiver.java

package com.example.broadcastReceiver;import com.example.service.MyService;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class AlarmReceiver extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent arg1) {        Intent intent = new Intent(context,MyService.class);        context.startService(intent);    }}

过程:
MainActivity→Myservice→AlarmReceiver→Myservice→AlarmReceiver

→Myservice→…(循环)

当服务启动,如果没有销毁服务,即使把程序关闭了,服务依然在进行

使用4大组件都要在androidManifest.xml注册,service和broadcastReceiver当然不例外

 <receiver             android:name="com.example.broadcastReceiver.AlarmReceiver">        </receiver>          <service android:name="com.example.service.MyService">        </service>

效果:
这里写图片描述

2016/02/15 更新

start方式特点:
-服务跟启动源没有任何关系
-无法得到服务对象

bind方式特点:
-通过Ibinder接口实例,返回一个ServiceConnection对象给启动源
-通过ServiceConnetcion对象的相关方法可以得到Service对象

0 0
原创粉丝点击