android 之 service

在Activity中设置两个按钮,分别为启动和关闭Service:

bt01.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(mainActivity.this, MyService.class);
                startService(i);
                Toast.makeText(mainActivity.this, "Service启动成功",
                        Toast.LENGTH_LONG).show();
            }
        });
        bt02.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(mainActivity.this, MyService.class);
                stopService(i);
                Toast.makeText(mainActivity.this, "Service启动成功",
                        Toast.LENGTH_LONG).show();
            }
        });

添加MyService.java

public class MyService extends Service {
    MyThread myThread;

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

    @Override
    public void onStart(Intent intent, int startId) {//启动Service
        // TODO Auto-generated method stub
        myThread = new MyThread();
        myThread.start();
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {//关闭Service
        // TODO Auto-generated method stub
        myThread.flag = false;
        super.onDestroy();
    }

    class MyThread extends Thread {
        boolean flag = true;
        int c = 0;

        public void run() {
            while (flag) {
               Intent i = new Intent("com.sunny.myThread");
                i.putExtra("myThread", c);
                sendBroadcast(i);//发送广播,在mainActivity中进行捕获,更新数据
                c++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

mainActivity中,添加广播接收器,过滤接收来自action为com.sunny.myThread的广播:

        IntentFilter intentFilter = new IntentFilter("com.sunny.myThread");
        MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
        registerReceiver(myBroadcastReceiverintentFilter);//注册广播接收器

其中:

class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Bundle myBundle = intent.getExtras();
            int myInt = myBundle.getInt("myThread");
                 tv01.setText("后台Service运行了" + myInt + "秒");
        }

    }

image

posted @ 2017-05-31 10:33  叶常绿  阅读(93)  评论(0编辑  收藏  举报
友情链接:回力鞋专卖店 | 中老年女装 | 武汉英语培训机构 | 经典电影 | 托福考试费用