服务Service,并与活动、接收器之间的通信

配置文件声明:

 <application
        。。。
        <activity android:name=".MainActivity">
           。。。
        </activity>
        <service android:name=".MyService"/>
        <service android:name=".MyIntentService"/>
        <service android:name=".LongRunningService"/>
        <receiver android:name=".AlarmReceiver"/>
    </application>

1.Service


/**
 * 1.服务需要在配置文件中声明。
 * 2.启动服务使用Intent。
 * 3.服务自行停止,只需要在MyService任何一个位置调用stopSelf()方法就行了。
 * 4.任何一个服务在整个应用程序范围内都是通用的,
 * 及MyService可以和任何一个活动进行绑定,
 * 而且在绑定完成后它们都可以获取到相同的DownloadBinder实例。
 * 5.当一个服务既被启动又被绑定后,需要同时调用stopService()和unbindService()方法,
 * onDestroy()才会执行。
 */

public class MyService extends Service{

    private DownloadBinder downloadBinder = new DownloadBinder();

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

    /**
     * 服务第一次创建的时候调用
     */
    @Override
    public void onCreate() {
        super.onCreate();
        ToastUtil.showMessage("服务创建");
        /*//创建一个前台服务
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                //设置小图标
                .setSmallIcon(R.mipmap.ic_launcher)
                //设置通知标题
                .setContentTitle("最简单的Notification")
                //设置点击后事件
                .setContentIntent(pendingIntent)
                //设置通知内容
                .setContentText("只有小图标、标题、内容");
        Notification notification = builder.build();
        startForeground(1, notification);*/
    }

    /**
     * 每次服务启动的时候都会调用
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
        ToastUtil.showMessage("服务启动");
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                //让服务执行完毕后自动停止
                stopSelf();
            }
        });*/
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ToastUtil.showMessage("服务销毁");
    }

    class DownloadBinder extends Binder{

        public void startDownload(){
            ToastUtil.showMessage("开始下载");
        }

        public int getProgress(){
            ToastUtil.showMessage("下载进度");
            return 0;
        }
    }
}

2.IntentService


public class MyIntentService extends IntentService{

    public MyIntentService() {
        super("MyIntentService");//调用父类的有参构造函数
    }

    /**
     * 处理一些具体的逻辑,运行在子线程中
     * @param intent
     */
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //显示当前线程的id
        ToastUtil.showMessage("MyIntentService当前线程的id:" + Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ToastUtil.showMessage("MyIntentService销毁");
    }
}

3.Service与BroadcastReceiver

LongRunningService :


/**
 * 一旦启动LongRunningService,就会在onStartCommand方法里设定一个定时任务,
 * 3秒后AlarmReceiver的onReceive方法就会得到执行,
 * 然后又在里面再次启动LongRunningService,这样就形成了一个永久的循环,
 * 保证LongRunningService可以每隔3秒就会启动一次。
 */

public class LongRunningService extends Service{

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("LongRunningService","onStartCommand");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("LongRunningService",new Date().toString());
            }
        }).start();
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int date = 3 * 1000;//3秒
        long triggerAtTime = SystemClock.elapsedRealtime() + date;
        Intent intent1 = new Intent(this,AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent1, 0);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent);
        return super.onStartCommand(intent, flags, startId);
    }
}

AlarmReceiver :


public class AlarmReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("AlarmReceiver","onReceive");
        Intent intent1 = new Intent(context, LongRunningService.class);
        context.startService(intent1);
    }
}

4.活动:

布局:添加几个按钮。

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.btn_start_service)
    Button btnStartService;
    @BindView(R.id.btn_stop_service)
    Button btnStopService;
    @BindView(R.id.btn_bind_service)
    Button btnBindService;
    @BindView(R.id.btn_unbind_service)
    Button btnUnbindService;
    @BindView(R.id.btn_start_intent_service)
    Button btnStartIntentService;
    @BindView(R.id.btn_start_long_running_service)
    Button btnStartLongRunningService;

    private MyService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {

        //服务成功绑定的时候调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        //服务解绑的时候调用
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

    @OnClick({R.id.btn_start_service, R.id.btn_stop_service,
            R.id.btn_bind_service, R.id.btn_unbind_service,
            R.id.btn_start_intent_service,
            R.id.btn_start_long_running_service})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.btn_start_service://启动服务
                intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
                break;
            case R.id.btn_stop_service://停止服务
                intent = new Intent(MainActivity.this, MyService.class);
                stopService(intent);
                break;
            case R.id.btn_bind_service://绑定服务
                intent = new Intent(MainActivity.this, MyService.class);
                bindService(intent, connection, BIND_AUTO_CREATE);
                //BIND_AUTO_CREATE表示在活动和服务进行绑定后自动创建服务,
                //这会使得MyService的onCreate方法得到执行,但onStartCommand方法不会执行。
                break;
            case R.id.btn_unbind_service://解绑服务
                unbindService(connection);
                break;
            case R.id.btn_start_intent_service:
                ToastUtil.showMessage("MainActivity当前线程的id:" + Thread.currentThread().getId());
                intent = new Intent(MainActivity.this, MyIntentService.class);
                startService(intent);
                break;
            case R.id.btn_start_long_running_service:
                intent = new Intent(MainActivity.this, LongRunningService.class);
                startService(intent);
                break;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值