传递数据后创建后台service来处理事件!

时间:2025-01-18 13:32:56

package com.lixu.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
//定义一个后台类
public class Myservice extends Service { @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
int[] nums=intent.getIntArrayExtra(Changliang.KEY);
int numhe=nums[0]+nums[1];
Toast.makeText(getApplicationContext(), numhe+"", 1).show();
return super.onStartCommand(intent, flags, startId);
} @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} }

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText; public class MainActivity extends Activity {
EditText et1;
EditText et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText) findViewById(R.id.et1);
et2=(EditText) findViewById(R.id.et2);
Button button=(Button) findViewById(R.id.btn1);
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Myservice.class);
int[] nums=new int[2];
nums[0]=Integer.parseInt(et1.getText().toString());
nums[1]=Integer.parseInt(et2.getText().toString());
intent.putExtra(Changliang.KEY, nums);
startService(intent);
}
});
} @Override
protected void onDestroy() {
//Activity销毁的时候关闭服务
Intent intent=new Intent(MainActivity.this,Myservice.class);
stopService(intent);
super.onDestroy();
} }

记住在manifest中注册service;

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <service android:name=".Myservice" >
</service>
</application>