Android Service串行服务:IntentService(系列3)

本文介绍了一个使用Android中的IntentService处理后台任务的具体实例。通过创建MyAppService类并继承IntentService,实现了接收Intent携带的数据,计算两个整数的和,并将结果广播出去的功能。此外,还展示了如何从MainActivity启动该服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class MyAppService extends IntentService{

//必须添加无参构造函数且super("MyAppService");MyAppService可以任写
public MyAppService() {
super("MyAppService");
// TODO Auto-generated constructor stub
}


@Override
protected void onHandleIntent(Intent intent) {

int[] data = intent.getIntArrayExtra(Constants.KEY);

int num = data[0] + data[1];
Log.d("2个数分别为    ", data[0]+"   "+data[1]);

Log.d("和 = ", num+"");
Intent it = new Intent(Constants.ACTION);
it.putExtra(Constants.KEY, data);
this.sendBroadcast(it);


}

}


开启服务

 Intent intent = new Intent(MainActivity.this,MyAppService.class);
 
 int[] data = new int[2];
 
 Random rand = new Random();
 
for(int i=0;i<data.length;i++){
 
data[i]=rand.nextInt(10);
}
intent.putExtra(Constants.KEY, data);
 startService(intent);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值