Service

来源:互联网 发布:final long java 编辑:程序博客网 时间:2024/06/09 23:12
1.服务是运行在后台的,可以用来做一些耗时的操作,后台并不是子线程,服务运行在主线程.
public class MainActivity extends AppCompatActivity {    ServiceConnection mConnection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            Log.e("TAG", "onServiceConnected: ------------");            MyService.MyBinder binder = (MyService.MyBinder) service;            binder.show("你是一个大傻逼..");        }        @Override        public void onServiceDisconnected(ComponentName name) {            Log.e("TAG", "onServiceDisconnected: ----------");        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button start = (Button) findViewById(R.id.start_service);        Button stop = (Button) findViewById(R.id.stop_service);        Button bind = (Button) findViewById(R.id.bind_service);        Button unbind = (Button) findViewById(R.id.unbind_service);//启动服务        start.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent =new Intent(MainActivity.this,MyService.class);                startService(intent);            }        });//停止服务        stop.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent =new Intent(MainActivity.this,MyService.class);                stopService(intent);            }        });//绑定服务        bind.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent =new Intent(MainActivity.this,MyService.class);                bindService(intent,mConnection,BIND_AUTO_CREATE);            }        });//取消服务的绑定        unbind.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                unbindService(mConnection);            }        });    }}

public class MyService extends Service {    private static final int NOTIFY_ID = 123;    private static int f = 0;    @Override    public void onCreate() {        Log.e(TAG, "onCreate: -------------:oncreat");        super.onCreate();        f=0;        NotificationCompat.Builder mBuilder =                new NotificationCompat.Builder(this)                        .setSmallIcon(R.drawable.ic_launcher)                        .setContentTitle(getText(R.string.title))                        .setContentText(getText(R.string.text));        // 创建通知被点击时触发的Intent        Intent resultIntent = new Intent(this, MainActivity.class);        // 创建任务栈Builder        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);        stackBuilder.addParentStack(MainActivity.class);        stackBuilder.addNextIntent(resultIntent);        PendingIntent resultPendingIntent =                stackBuilder.getPendingIntent(                        0, PendingIntent.FLAG_UPDATE_CURRENT);        mBuilder.setContentIntent(resultPendingIntent);        NotificationManager mNotifyMgr =                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        // 构建通知        final Notification notification = mBuilder.build() ;        // 显示通知        mNotifyMgr.notify(NOTIFY_ID, notification);        // 启动为前台服务        startForeground(NOTIFY_ID, notification);        new Thread(new Runnable() {            @Override            public void run() {                while (f==0){                    //startForeground(NOTIFY_ID, notification);                    Log.e(TAG, "run: --------------");                }            }        }).start();        Notification no =new Notification();            }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.e(TAG, "onStartCommand: ---------------:onstartcommand");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        Log.e(TAG, "onDestroy: --------------:ondestroy");        f=1;        super.onDestroy();    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        Log.e(TAG, "onBind: ------------------:onbind");        return new MyBinder();    }    @Override    public boolean onUnbind(Intent intent) {        Log.e(TAG, "onUnbind: ------------------:onunbind");        return super.onUnbind(intent);    }    class MyBinder extends Binder{        public void show(String name){            Log.e(TAG, "show: --------------:name :"+name);            new Thread(new Runnable() {                @Override                public void run() {                    Log.e(TAG, "run: ----------------创建子线程执行耗时任务.");                }            });        }    }
//自身提供的停止服务的方法
     @Override     public boolean stopService(Intent name) {    return super.stopService(name);    }
}
注意细节:
1.服务运行在主线程
2.启动startService(intent);
3.停止服务 stopServiece() 和 stopSelf()();
4.服务中oncreat方法中添加子线程来做耗时操作;
5. 4中的子线程不会通过stopservice 或者stopself 而停止,只有在ondestoy方法中关闭子线程.或者程序关闭.
6.startservice并且bindservice了,那么就要stopservice 和 unbindservice才能停止服务.
7.unbindservice只能解绑未解绑的服务,如果解绑已经解绑的服务,则程序会报异常.
8.通过notification,来将服务变成前台service,这样就不会因为内存不足而被系统杀死.
9.服务可以通过远程服务来实现进程间通信,如AIDL.
原创粉丝点击