1,首先建立服务类
ExampleService.java
package com.dd.dd;
import com.dd.dd.dao.StudentDao;
import com.dd.dd.model.Student;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class ExampleService extends Service {
private static final String TAG = "ExampleService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
Log.i(TAG, "ExampleService-->onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
Log.i(TAG, "ExampleService-->onDestroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this.getApplicationContext();
System.out.println("context:" + context);
StudentDao studentDao = new StudentDao(context);
Student student = new Student();
student.setId(8);
student.setName("师远鹏");
studentDao.add(student);
Log.i(TAG, "添加成功!");
return super.onStartCommand(intent, flags, startId);
}
}
2,在AndroidManifest.xml添加服务 是在 </activity>外 </application>内添加的
<service android:name=".ExampleService" />
3,最后一步就是添加按钮事件
add = (Button) findViewById(R.id.add);
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
ExampleService.class);
Toast.makeText(MainActivity.this, "已经成功添加了数据!",
Toast.LENGTH_LONG).show();
startService(intent);
Log.i(TAG, "成功添加了");
}
});
然后就o啦