android 之 service

Posted 叶常绿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于android 之 service的主要内容,如果未能解决你的问题,请参考以下文章

Android基础系列合集

android Service学习

Android Service总结

清单文件-服务标签

android 百度地图

Android学习总结——Service组件