Android__Service

服务使程序实现后台运行,服务一般包含线程,线程依赖于应用进程,同理服务也是依赖
每一个创建该服务的应用进程,每一个打开的应用程序可以成为一个进程。
可成为一个进程,服务并不会自动开启线程,所有的代码都是默认在主线程里面运行的,
所以一般是在服务里面创建子线程,否则就可能出现主线程被阻塞的情况。

Android线程:
如果想进行UI操作,在子线程里是不能实现的,必须到主线程才能实现,一般在子线程
进行hanlder.sendMessage(message)—–然后在handler里进行逻辑操作

private Handler handler = new Handler(){

    public void handleMessage(Message msg){
        //逻辑操作
    }
};

线程信息的处理机制图:
线程图

Sevice(服务):

服务的生命周期:onBind(),onCreate(),onStartCommand(),onDestroy()

public class MyService extends Service {


    private DownLoadBinder mBinder = new DownLoadBinder();
    //实现活动和服务的通信或者使联系更紧密
    //创建一个实例,然后再onBind()里面返回一个实例,然后再MainActivity中
    //新建ServiceConnection对象,在这对象里面重写两个方法,实现对mBlid
    //实例的调用
    class DownLoadBinder extends Binder{

        public void startDownload(){
            Log.d("MyService", "startDownload");

        }

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

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return mBinder;
    }

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

        //前台服务用法
        Notification notification = new Notification(R.drawable.ic_launcher, "Notification", 
                System.currentTimeMillis());
        Intent notificationItent = new Intent(this,MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationItent,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");
        return super.onStartCommand(intent, flags, startId);
        //逻辑操作,在这里一般创建子线程


    }

    @Override
    public void onDestroy(){

        super.onDestroy();
        Log.d("MyService", "onDestroy executed");
    }

}
public class MainActivity extends Activity implements OnClickListener{

    private Button startService;
    private Button stopService;

    private Button startIntentService;

    //实现活动和服务的联系即是绑定服务
    private Button blind;
    private Button Unblind;

    //由于定义了一个内部类,所以要调用内部类的对象则
    private MyService.DownLoadBinder downLoadBinder;

    //然后还要通过一个ServiceConnection 实现对两个方法的调用
    //serviceConnection,在绑定和解绑服务传入
    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
//          Log.d("MyService", "unblinder OK");

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            downLoadBinder = (MyService.DownLoadBinder)service;

            downLoadBinder.startDownload();
            downLoadBinder.getProgress();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);


        startIntentService = (Button)findViewById(R.id.intent_service_button);
        startService = (Button)findViewById(R.id.start_service_button);
        stopService = (Button)findViewById(R.id.stop_service_button);
        blind = (Button)findViewById(R.id.bind_service_button);
        Unblind = (Button)findViewById(R.id.ubind_service_button);


        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        blind.setOnClickListener(this);
        Unblind.setOnClickListener(this);
        startIntentService.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
        case R.id.start_service_button:

            Intent startIntent = new Intent(this,MyService.class);
            //开启服务
            startService(startIntent);
            Toast.makeText(this, "开启服务", Toast.LENGTH_SHORT).show();
            break;

        case R.id.stop_service_button:

            Intent stopIntent = new Intent(this,MyService.class);
            stopService(stopIntent);
            Toast.makeText(this, "关闭服务", Toast.LENGTH_SHORT).show();
            break;

        case R.id.bind_service_button:

            Intent bindIntent = new Intent(this,MyService.class);
            bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
            //绑定服务
            break;

        case R.id.ubind_service_button:
            //解绑服务
            unbindService(serviceConnection);
            break;

        case R.id.intent_service_button:

            Log.d("MainActivity", "Thread id is "+Thread.currentThread().getId());
            Intent intentService = new Intent(this,MyIntentService.class);
            startService(intentService);

            break;
        default:

            break;

        }
    }
}

标准服务案例:
定时启动服务,实现定时操作

//AlarmManager对象
    LongService extends Service{
        onStartCommand(){
            new Thread(new Runnable(){
                @Override
                public void run(){

                }
            }).start();
        }
    }
//这里是实现的是定时执行任务,只要把任务
Log.d("LongRunningService", "executed at "+new Date().toString());替换就可以


public class LongRunningService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

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

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                //执行任务
                Log.d("LongRunningService", "executed at "+new Date().toString());
            }
        }).start();

        //AlarmManager 对象
        AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);

        int laytime = 6*1000;

        long triggerAtTime = SystemClock.elapsedRealtime()+laytime;
        Intent i = new Intent(this,AlarmReceiver.class);



        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);


        //定时时间从系统开机开始,唤醒CPU
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime , pi);
        //在这里的执行到广播接收器里面开启了新的服务,然后在广播接收器和LongRunningService不断循环不断执行任务

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

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Intent i = new Intent(context,LongRunningService.class);

        context.startService(i);
    }

}
public class MainActivity extends Activity {
    @Override
    protected  void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Intent i = new Intent(this,LongRunningService.class);
        startService(i);
    }
}
//别忘了在
<application> 
    <service android:name=".LongRunningService"></service>
    <receiver android:name=".AlarmReceiver"></receiver>
</application>
分析: 首先从MainActivity开始启动
        Intent i = new Intent(this,LongRunningService.class);
        startService(i);
        在LongRunningService.class启动了AlarmReceiver

        在AlarmReceiver中又启动了LongRunningService.class

        这样不断循坏开始
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值