Android使用bindService启动服务

Posted CSlunatic

tags:

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

 

以上是关于Android使用bindService启动服务的主要内容,如果未能解决你的问题,请参考以下文章

Android使用bindService启动服务

bindService启动过程-Android12

bindService启动过程-Android12

Android 源码分析 bindService 启动

Android 源码分析 bindService 启动

Android 源码分析 bindService 启动