zoukankan
html css js c++ java
安卓四大组件之Sevice组件的简单使用 --Android基础
1、本例实现了简单的Service(服务)的创建、启动和停止,点击“启动SERVICE”页面会显示“服务被创建”,接着是“服务被启动”。点击“停止SERVICE”页面提示“服务被停止”。太过基础,直接贴代码了……新手看看,老司机就忽略吧……
2、基本代码
ServiceDemo:
package thonlon.example.cn.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
/**
*
绑定服务的时候被调用
*/
public class ServiceDemo extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Service被创建后被调用
*/
@Override
public void onCreate() {
Toast.makeText(ServiceDemo.this,"服务被创建",Toast.LENGTH_SHORT).show();
Log.d("onCreate", "服务被创建");
}
/**
* Service被开始后调用
*
* @param intent
* @param flags
* @param startId
* @return
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(ServiceDemo.this,"服务被启动",Toast.LENGTH_SHORT).show();
Log.d("onStartCommand", "服务被启动");
return super.onStartCommand(intent, flags, startId);
}
/**
* Service被停止后调用
*/
@Override
public void onDestroy() {
Toast.makeText(ServiceDemo.this,"服务被停止",Toast.LENGTH_SHORT).show();
Log.d("onDestroy", "服务被停止");
}
}
MainActivity:
package thonlon.example.cn.servicedemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(this,ServiceDemo.class);
switch (v.getId()){
case R.id.btn_start_service://第一次点启动Service,服务会被创建,之后再点击启动服务不会再被创建,服务已经被创建
startService(intent);
break;
case R.id.btn_stop_service:
stopService(intent);
break;
}
}
}
查看全文
相关阅读:
juc线程池原理(六):jdk线程池中的设计模式
阻塞队列之一:BlockingQueue汇总
阻塞队列之二:LinkedTransferQueue
遍历并批量删除容器中元素出现ConcurrentModificationException原因及处置
Spring 3.1新特性之一:spring注解之@profile
ThreadPoolExecutor之三:自定义线程池-扩展示例
守护线程
cookie跨域问题汇总
线程组ThreadGroup
Eclipse中设置JDK、${user}变量
原文地址:https://www.cnblogs.com/qikeyishu/p/9186022.html
最新文章
[转]Getting started with SSIS
[转]SSIS中OLE DB Source中如何执行Store Procedure 以得到源数据
[转]SSIS OLE DB Source中执行带参数的存储过程
[转]Working with Parameters and Return Codes in the Execute SQL Task
[转]How to solve SSIS error code 0xC020801C/0xC004700C/0xC0047017
[转]ssis cannot retrieve the column code page info from the ole db provider
[转]使用SSIS创建同步数据库数据任务
[转]sqlserver2008锁表语句详解
effective java 笔记1--序言
Spring启动后获取所有拥有特定注解的Bean,注解的属性值
热门文章
利用 Ant 和 Eclipse 有效地提高部署工作效率
Effective java笔记4--方法
代码审查的价值——为何做、何时做、如何做?
Effective java笔记3--类和接口2
根据当前日期算前一年、前一月、前一天(java基础)
Effective java笔记3--类和接口1
Effective java笔记2--创建于销毁对象
juc线程池原理(四): 线程池状态介绍
juc线程池原理(五):拒绝策略示例
Annotation之一:Java Annotation基本功能介绍
Copyright © 2011-2022 走看看