android基础之四——广播与服务(二)

01_start开启服务的生命周期(重点)

  • 服务的特点:

    服务被创建时调用onCreate、onStartCommand;
    服务只能被创建一次,可以开启多次onStartCommand;
    服务只能被停止一次onDestroy; 
    没有onPause、onStop、onResume、onRestart方法,因为service没有界面,长期运行在后台。
    
  • 生命周期的方法:

    onCreate:服务被创建的时候调用这个方法;
    onStartCommand :开启服务;
    onDestroy:销毁服务;
    

02_bind方式开启服务的生命周期(重点)

bindService、unbindService的特点:

1、第一次绑定服务时,先创建服务对象,在绑定,调用了oncreate onbind;
2、解除绑定的服务时,调用onUnbind、onDestroy;
3、服务只能被帮顶一次;
4、服务只能被解除一次,多次解除程序会抛出异常;
5、使用bindservice方式开启的服务,会随着界面的退出而解除绑定并且销毁服务对象;

生命周期:

1、第一次绑定服务时创建服务对象:onCreate、onbind;
2、界面关闭时销毁服务对象:onUnbind、onDestroy;

推荐的混合方式:
1、startService:可以让服务长期运行在后台;
2、bindService:绑定服务,为了调用服务的业务逻辑方法;
3、unbindService:解除绑定,不能在调用服务里业务逻辑方法;
4、stopService:停止服务,销毁服务对象;

03_为什么要引入bindservice的API

目的:为了调用服务中业务逻辑方法:

04_绑定服务调用服务方法的过程

通过中间人调用服务里面的业务逻辑方法:

1、在服务中添加一个中间人的类,这个类继承了Binder,Binder实现了IBinder接口,所以中间人就是一个IBinder的实现类;
2、在绑定服务时调用的onBind方法返回中间人对象;
3、在activity中绑定服务成功时获取中间人对象;
4、在activity中调用中间人的方法(这个方法中调用服务的业务逻辑方法);

代码:

MainActivity.java:

package com.itheima.bindservice;

import com.itheima.bindservice.TestService.MyBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

public class MainActivity extends Activity {

private MyConn conn;
private Intent intent;

//中间人对象
private MyBinder myBinder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void call(View view) {
    myBinder.callMethodInService();
}

public void start(View view) {
    intent = new Intent(this, TestService.class);
    startService(intent);
}

public void stop(View view) {
    stopService(intent);
}

public void bind(View view) {

    conn = new MyConn();
    // 绑定服务
    // intent开启服务的意图对象
    // MyConn在activity与service之间创建的一个连接,作为通讯的渠道
    // BIND_AUTO_CREATE 绑定服务时如果服务不存在,就会县创建一个服务对象,然后在绑定
    bindService(intent, conn, BIND_AUTO_CREATE);
}

public void unbind(View view) {
    //解除绑定
    unbindService(conn);
}

private class MyConn implements ServiceConnection {

    /**
     * 服务绑定成功后调用这个方法
     */
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

        myBinder = (MyBinder) service;
    }

    /**
     * 解除服务成功时调用这个方法
     */
    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
    }
}
}

TestService.java:

package com.itheima.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class TestService extends Service {

/*
 * 绑定服务的时候会调用这个方法
 * return : 绑定服务成功后返回一个IBinder类型的数据对象
 */
@Override
public IBinder onBind(Intent arg0) {
    System.out.println("--------onBind---------");
    return new MyBinder();
}

/**
 * 解除绑定的服务时调用这个方法
 */
@Override
public boolean onUnbind(Intent intent) {
    System.out.println("--------onUnbind---------");
    return super.onUnbind(intent);
}


@Override
public void onCreate() {
    System.out.println("--------onCreate---------");
    super.onCreate();
}

@Override
public void onDestroy() {
    System.out.println("--------onDestroy---------");
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("--------onStartCommand---------");
    return super.onStartCommand(intent, flags, startId);
}

/**
 * 业务逻辑方法
 */
public void methodInService(){
    System.out.println("========methodInService========");
}

/**
 * 中间人,
 * @author Administrator
 *
 */
public class MyBinder extends Binder{

    public void callMethodInService(){
        //调用业务逻辑方法
        methodInService();
    }
}
}

05_绑定服务抽取接口(重点)

接口的作用:对外暴露功能,隐藏实现的细节;

步骤:
1、创建一个接口,里面写一个方法(对外暴露的方法):
2、在服务类里面,让中间人实现这个接口,并且实现接口中方法,在实现的方法中调用服务的业务逻辑方法;
3、在activity中绑定服务成功时,得到接口类型的中间人对象;
4、在activity中调用中间人的方法;

代码:

MainActivity.java:

package com.itheima.bindservice;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

public class MainActivity extends Activity {

private MyConn conn;
private Intent intent;
//中间人对象
private IService myBinder;

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


public void call(View view) {
    myBinder.callMethodInService();
}

public void start(View view) {
    intent = new Intent(this, TestService.class);
    startService(intent);
}

public void stop(View view) {
    stopService(intent);
}

public void bind(View view) {
    conn = new MyConn();
    // 绑定服务
    // intent开启服务的意图对象
    // MyConn在activity与service之间创建的一个连接,作为通讯的渠道
    // BIND_AUTO_CREATE 绑定服务时如果服务不存在,就会县创建一个服务对象,然后在绑定
    bindService(intent, conn, BIND_AUTO_CREATE);
}

public void unbind(View view) {
    //解除绑定
    unbindService(conn);
}

private class MyConn implements ServiceConnection {

    /**
     * 服务绑定成功后调用这个方法
     */
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        myBinder = (IService) service;
    }

    /**
     * 解除服务成功时调用这个方法
     */
    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
    }
}
}

TestService.java:

package com.itheima.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class TestService extends Service {

/*
 * 绑定服务的时候会调用这个方法
 * return : 绑定服务成功后返回一个IBinder类型的数据对象
 */
@Override
public IBinder onBind(Intent arg0) {
    System.out.println("--------onBind---------");
    return new MyBinder();
}

/**
 * 解除绑定的服务时调用这个方法
 */
@Override
public boolean onUnbind(Intent intent) {
    System.out.println("--------onUnbind---------");
    return super.onUnbind(intent);
}


@Override
public void onCreate() {
    System.out.println("--------onCreate---------");
    super.onCreate();
}

@Override
public void onDestroy() {
    System.out.println("--------onDestroy---------");
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("--------onStartCommand---------");
    return super.onStartCommand(intent, flags, startId);
}

/**
 * 业务逻辑方法
 */
public void methodInService(){
    System.out.println("========methodInService========");
}

/**
 * 中间人,
 * @author Administrator
 *
 */
private class MyBinder extends Binder implements IService{

    //实现接口中方法
    public void callMethodInService(){
        //调用业务逻辑方法
        methodInService();
    }

    public void eat(){
        System.out.println("=======eat======");
    }

    public void sn(){
        System.out.println("=======sn======");
    }

    public void ktv(){
        System.out.println("=======ktv======");
    }
    }
}

06_服务的应用场景

应用场景:需要在后台运行一个程序,需要与服务器端通讯数据;
常见的服务应用场景:天气预报、股票软件;

07_利用服务注册广播接收者

 使用代码注册广播接收者原因:操作比较频繁的事件,在激活广播接收者时,需要去读取清单文件,解析xml格式的数据,这个过程占用的资源比较大,耗时较长。

 使用代码注册的广播接收者,启动的时候比较快。

工程代码:

  • 配置文件:

    <receiver android:name="com.itheima.coderegistreceiver.ScreenBroadcastreceiver">
    </receiver>
    
    <service android:name="com.itheima.coderegistreceiver.ScreenReceiverService"></service>
    
  • 代码:

    public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        Intent intent = new Intent(this,ScreenReceiverService.class);
        startService(intent);
    }
    }
    

    ScreenReceiverService.java:

        package com.itheima.coderegistreceiver;
    
        import android.app.Service;
        import android.content.Intent;
        import android.content.IntentFilter;
        import android.os.IBinder;
    
        public class ScreenReceiverService extends Service {
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            // 1、创建一个广播接收者的对象
            ScreenBroadcastreceiver receiver = new ScreenBroadcastreceiver();
            // 2、为广播接收者创建意图过滤器
            IntentFilter filter = new IntentFilter();
            // 3、在意图过滤器中设置广播接收者需要接收的事件类型
            filter.addAction("android.intent.action.SCREEN_ON");
            filter.addAction("android.intent.action.SCREEN_OFF");
            // 4、注册广播接收者
            this.registerReceiver(receiver, filter);
        }
    }
    

08_远程服务aidl的写法(重点)

远程服务:在同一个设备上安装的其他应用程序,包含一个服务的应用程序。
本地服务:在自己的应用程序中写另一个服务的类;


aidl: Android Interface Definition language 安卓的接口定义语言;
这个格式的文件,就是对外共享的接口的文件,可以把这个文件拷贝任何工程里,可以调用远程服务的接口;

IPC: Inter Process Communication 进程间的通讯;

在本地应用程序中调用远程的服务接口:

步骤: 1、写远程的工程,写一个服务; (1)创建一个服务类,重写了onBind方法; (2)在服务类里写了一个中间人,继承了Binder; (3)写一个接口类,对外暴露了一个方法; (4)在服务类里让中间人实现了这个接口,重写接口的方法(在这个方法里面调用服务的业务逻辑方法); (5)修改IService类的格式,改成aidl格式(让它作为一个对外开放的共享接口文件); (6)让中间人继承Stub; 2、创建一个本地应用程序,调用远程的服务接口: (1)创建一个与远程服务相同的包名,然后把aidl文件拷贝到这个包里; (2)在activity中绑定服务成功时得到IService类型的中间人; (3)在activity中调用中间人的方法;

远程服务:

package com.itheima.remoteservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.itheima.remoteservice.IService.Stub;

public class RemoteService extends Service {

@Override
public IBinder onBind(Intent intent) {
    System.out.println("=========onBind============");
    return new MyBinder();
}

public void methodInService(){
    System.out.println("================methodInService===========");
}



//中间人 继承 Stub,能够是进程间的通讯
private class MyBinder extends Stub{

    @Override
    public void callMethodInService() {
        //调用服务的业务逻辑方法
        methodInService();
    }

}

}

本地应用程序:

package com.itheima.localapp;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;

import com.itheima.remoteservice.IService;
import com.itheima.remoteservice.IService.Stub;

public class MainActivity extends Activity {

private IService myBinder;

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

public void bind(View view ){
    Intent intent = new Intent();
    intent.setAction("com.itheima.remoteservice.REMOTESERVICE");

    //绑定服务
    bindService(intent, new MyConn(), BIND_AUTO_CREATE);
}


public void call(View view ){
    try {
        //调用远程服务接口的方法
        myBinder.callMethodInService();
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

private class MyConn implements ServiceConnection{

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        //把中间人作为接口来使用
        myBinder = Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

}

}

09_帧动画(重点)

帧动画:有一组图片,按照一定的序列一帧一帧的播放,这个变化的过程;

代码:

package com.itheima.drawableamin;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    iv = (ImageView) findViewById(R.id.iv);

    //给imageview添加背景资源
    iv.setBackgroundResource(R.drawable.girl);
    //得到帧动画对象
    AnimationDrawable ad = (AnimationDrawable) iv.getBackground();

    //播放动画
    ad.start();
}
}

xml文件:

    <?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false"
     >

    <item
        android:drawable="@drawable/girl_1"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_2"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_3"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_4"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_5"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_6"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_7"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_6"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_7"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_6"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_7"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_8"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_9"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_10"
        android:duration="200"/>
    <item
        android:drawable="@drawable/girl_11"
        android:duration="200"/>

</animation-list>

10_补间动画

补间动画:图片的平移、旋转、缩放、透明度等变化的过程;

透明度:alpha
平移:translate
旋转:rotate
缩放:scale

代码:

package com.itheima.tweensanmi;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

public class MainActivity extends Activity {

private ImageView iv;

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

    iv = (ImageView) findViewById(R.id.iv);
}

public void alpha(View view) {
    // fromAlpha 开始透明度 0表示完全透明,1.0表示完全不透明
    // toAlpha 结束透明度
    AlphaAnimation aa = new AlphaAnimation(0, 1.0f);
    // 设置动画播放的时间长度
    aa.setDuration(3000);
    // 设置重复播放的次数
    aa.setRepeatCount(2);
    // 设置重复播放的模式
    aa.setRepeatMode(AlphaAnimation.REVERSE);
    // 在imageview上播放动画
    iv.startAnimation(aa);
}

public void rotate(View view) {

    RotateAnimation ra = new RotateAnimation(0, 360,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    // 设置动画播放的时间长度
    ra.setDuration(3000);
    // 设置重复播放的次数
    ra.setRepeatCount(2);
    // 设置重复播放的模式
    ra.setRepeatMode(RotateAnimation.REVERSE);
    // 在imageview上播放动画
    iv.startAnimation(ra);
}

public void scale(View view) {

    ScaleAnimation sa = new ScaleAnimation(0, 1.0f, 0, 1.0f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    // 设置动画播放的时间长度
    sa.setDuration(3000);
    // 设置重复播放的次数
    sa.setRepeatCount(2);
    // 设置重复播放的模式
    sa.setRepeatMode(ScaleAnimation.REVERSE);
    // 在imageview上播放动画
    iv.startAnimation(sa);
}

public void trans(View view) {

    TranslateAnimation sa = new TranslateAnimation(0, 200, 0, 200);
    // 设置动画播放的时间长度
    sa.setDuration(3000);
    // 设置重复播放的次数
    sa.setRepeatCount(2);
    // 设置重复播放的模式
    sa.setRepeatMode(ScaleAnimation.REVERSE);
    // 在imageview上播放动画
    iv.startAnimation(sa);
}


public void set(View view) {


    AnimationSet set = new AnimationSet(false);

    AlphaAnimation aa = new AlphaAnimation(0, 1.0f);
    // 设置动画播放的时间长度
    aa.setDuration(3000);
    // 设置重复播放的次数
    aa.setRepeatCount(2);
    // 设置重复播放的模式
    aa.setRepeatMode(AlphaAnimation.REVERSE);

    set.addAnimation(aa);

    RotateAnimation ra = new RotateAnimation(0, 360,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    // 设置动画播放的时间长度
    ra.setDuration(3000);
    // 设置重复播放的次数
    ra.setRepeatCount(2);
    // 设置重复播放的模式
    ra.setRepeatMode(RotateAnimation.REVERSE);
    set.addAnimation(ra);

    ScaleAnimation sa = new ScaleAnimation(0, 1.0f, 0, 1.0f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    // 设置动画播放的时间长度
    sa.setDuration(3000);
    // 设置重复播放的次数
    sa.setRepeatCount(2);
    // 设置重复播放的模式
    sa.setRepeatMode(ScaleAnimation.REVERSE);
    set.addAnimation(sa);


    TranslateAnimation ta = new TranslateAnimation(0, 200, 0, 200);
    // 设置动画播放的时间长度
    ta.setDuration(3000);
    // 设置重复播放的次数
    ta.setRepeatCount(2);
    // 设置重复播放的模式
    ta.setRepeatMode(TranslateAnimation.REVERSE);

    set.addAnimation(ta);
    //播放动画集合
    iv.startAnimation(set);
}
}

11_对话框合集

对话框:

1、Toast:

2、确定取消的对话框:
3、单选对话框:
4、复选对话框:
5、进度对话框:
6、进度条对话框:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值