Android使用bindService启动服务

1.Service

package com.example.ebobo;

import java.util.Timer;

import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.os.Binder;

public class timer_push extends Service {

    private NotificationManager manager;
    private Notification myNotify;
    private Context context;
    private PendingIntent contentIntent;
    private CharSequence contentTitle;
    private CharSequence contentText;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;  

    private final IBinder binder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class MyBinder extends Binder {
        timer_push getService() {
            return timer_push.this;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // 当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
        System.out.println("调用者退出了");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.i("push_service", "push_service onCreate");

        manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.drawable.button_login; //通知图标
        CharSequence tickerText = "Hello"; //状态栏显示的通知文本提示
        long when = System.currentTimeMillis(); //通知产生的时间,会在通知信息里显示
        myNotify = new Notification(icon,tickerText,when);
        myNotify.defaults = Notification.DEFAULT_VIBRATE; 

        context = getApplicationContext(); //上下文
        contentTitle = "定时按摩"; //通知栏标题
        Intent notificationIntent = new Intent(getApplicationContext(), ScanActivity.class); //点击该通知后要跳转的Activity
        contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent,int startId)
    {
        super.onStart(intent, startId);
        Log.i("push_service", "push_service start");
    }

    @Override
    public void onDestroy()
    {
        stopMyTimer();
        manager.cancel(2);
        super.onDestroy();
        Log.i("push_service", "push_service destroy");
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 123:
                contentText = "请注意大保健!"; //通知栏内容
                myNotify.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
                manager.notify(2, myNotify);
                //如果想要更新一个通知,只需要在设置好notification之后,再次调用 setLatestEventInfo(),然后重新发送一次通知即可,即再次调用notify()。
                break;

            default:
                break;
            }
        }
    };

    public  void startMyTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }  

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    do {
                       try {
                           Log.i("push_service", "222222222222222222222222222222222222222y");
                            Message message = new Message();
                            message.what = 123;
                            handler.sendMessage(message);
                        }
                        catch (IllegalStateException e) {
                        }
                    } while (false);
                }
            };
        }  

        if(mTimer != null && mTimerTask != null )
            mTimer.schedule(mTimerTask, 0, 10000);
    }  

    public  void stopMyTimer(){  

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }  

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
}

2 activity1

public class LoginActivity extends Activity implements OnClickListener, OnCheckedChangeListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Intent intent = new Intent(this, timer_push.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE); 

        init();
    }
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = ((timer_push.MyBinder) service).getService();
            System.out.println("Service连接成功");
            // 执行Service内部自己的方法
            myService.startMyTimer();
        }
    };
}

3.actvity2

public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mian_water);

        init();

        model = 0;

        Intent sintent = new Intent(this, timer_push.class);
        bindService(sintent, connection, Context.BIND_AUTO_CREATE);
    }

        private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = ((timer_push.MyBinder) service).getService();
            System.out.println("Service连接成功");
        }
    };

    public void onClick(View v) {
      switch (v.getId()) {
      case R.id.btn_wf_start:
            index = 3;
            if(btnStart.getText().toString().equals(getResources().getString(R.string.start))){
                btnStart.setText(getResources().getString(R.string.stop));
                startMyTimer();

                getflag = 1;

                final ProgressDialog proDia=ProgressDialog.show(WaterActivity.this,"",
                                                                "正在启动设备,请稍后...",true,false);// 执行Service内部自己的方法
                myService.stopMyTimer();
            } else {// 执行Service内部自己的方法
                myService.startMyTimer();
            }
       }
   }
}    
时间: 2025-01-18 10:48:34

Android使用bindService启动服务的相关文章

Android中bindService的使用及Service生命周期

Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context的bindService方法,本文只探讨纯bindService的使用,不涉及任何startService方法调用的情况.如果想了解startService相关的使用,请参见<Android中startService的使用及Service生命周期>. bindService启动服务的特点 相比于用startService启动的Service,bindService启动的服务

Android 两种启动Service(远程)的方式:Bind 与Start

前言:本文主要讨论启动远程Service. Service和Activity不在一个工程里面,也即不在一个App里面.不在一个进程里,所以会用到AIDL. Service的android:process属性未指定. 一.startService 1.通过调用startService启动服务的过程: onCreate ->onStartCommand ->onStart startService 仅用于启动服务,如果Activity需要与Service进行通信,需利用Broadcast. 2.而

Android应用程序绑定服务(bindService)的过程源代码分析

文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6745181 Android应用程序组件Service与Activity一样,既可以在新的进程中启动,也可以在应用程序进程内部 启动:前面我们已经分析了在新的进程中启动Service的过程,本文将要介绍在应用程序内部绑定Service的过程,这是一种在应用程序进程内部启动 Service的方法. 在前面一篇文章Android进程间通信(IPC)机

Android四大组件之服务的两种启动方式详解

Service简单概述 Service(服务):是一个没有用户界面.可以在后台长期运行且可以执行操作的应用组件.服务可由其他应用组件启动(如:Activity.另一个service).此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信 (IPC).例如:服务可以处理网络事务.播放音乐,执行文件 I/O 或与内容提供程序交互,而这一切均可在后台进行. 进程的优先级 了解进程的优先级可以帮助你理解服务~ 1. Foreground process(前台进程) 一句话总结:当前跟用户有交互

android开发教程之开机启动服务service示例

个例子实现的功能是:1,安装程序后看的一个Activity程序界面,里面有个按钮,点击按钮就会启动一个Service服务,此时在设置程序管理里面会看的有个Activity和一个Service服务运行2,如果手机关机重启,会触发你的程序里面的Service服务,当然,手机启动后是看不到你的程序界面.好比手机里面自带的闹钟功能,手机重启看不到闹钟设置界面只是启动服务,时间到了,闹钟就好响铃提醒. 程序代码是: 首先要有一个用于开机启动的Activity,给你们的按钮设置OnClickListener

android:启动服务;广播(最高优先窃听信息)并转发给别人

3.1.Service服务 Service类似Activity,实际上就是一个没有界面的Activity,而且默认不会随着程序关闭而关闭. 开发人员自定义的服务类一般用来完成一些安全软件的一些监听功能,以及消息提示,流氓软件的功能. 系统服务则是通过类似getSystemService()的方法来取得系统的一些服务管理类(XxxxManager),来调用系统处理好的功能完成自己需要的操作,例如:电话监听,连接状态的判断等. 如果想自己编写一个服务类,可以建立一个类,继承Service,并覆写相应

android SystemServer.java启动的服务有哪些?

EntropyService:熵(shang)服务,用于产生随机数 PowerManagerService:电源管理服务 ActivityManagerService:最核心服务之一,Activity管理服务 TelephonyRegistry:电话服务,电话底层通知服务 PackageManagerService:程序包管理服务 AccountManagerService:联系人帐户管理服务 ContentService:内容提供器的服务,提供跨进程数据交换 LightsService:光感应

Android 四大组件 Service 服务

1.Service简介 按照使用范围分类: 类别 优点 缺点 区别 应用 本地服务 Local  Service 本地服务在一定程度上节约了资源,另外本地服务因为是在同一进程,因此不需要IPC,也不需要AIDL.相应bindService会方便很多. 主进程被Kill后,服务便会终止. 本地服务依附在主进程上,而不是独立的进程,用于应用程序内部 . 音乐播放服务 远程服务 Remote Service 对应进程名格式为所在包名加上指定的android:process字符串.由于是独立的进程,因此

一个Demo学完Android中所有的服务(转)

说明:这个例子实现了Android中常见的许多服务,下面是实现的截图 接下来,以源代码的方式分析这个例子   1.MainActivity--主界面 这个类主要是实现用户所看到的这个Activity,其中包含了一系列的按钮,用户点击按钮执行相应的动作,所以在这个类中主要是对按钮的定义和对按钮绑定相应的监听器,下面是实现的代码: [java] view plaincopyprint? package lovefang.stadyService; import android.app.Activit