package com.example.service;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public static final String KEY="my_key";
private EditText et1,et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText) findViewById(R.id.editText1);
et2=(EditText) findViewById(R.id.editText2);
Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int[] data=new int[2];
data[0]=Integer.parseInt(et1.getText()+"");
data[1]=Integer.parseInt(et2.getText()+"");
Intent intent = new Intent(MainActivity.this,MyAppService.class);
intent.putExtra(KEY,data);
startService(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this,MyAppService.class);
stopService(intent);
}
}
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyAppService extends Service{
public static final String KEY="my_key";
@Override
public void onCreate() {
super.onCreate();
}
// 在这里处理耗时、后台、无需用户交互的‘重口味’操作
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int [] data=intent.getIntArrayExtra(KEY);
int nums=data[0]+data[1];
Toast.makeText(getApplicationContext(), nums+"", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
Log.d("服务日志","销毁");
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.service.MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="45dp"
android:text="计算" />
</LinearLayout>
<service android:name=".MyAppService"/>