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);