这里只说重要的代码
1,首先创建StudentService.java
package com.dd.dd; import com.dd.dd.dao.StudentDao; import com.dd.dd.model.Student; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.util.Log; public class StudentService extends IntentService { private static final String TAG = "StudentService"; public StudentService() { super("StudentService"); } @Override protected void onHandleIntent(Intent arg0) { Context context = this.getApplicationContext(); System.out.println("context:" + context); StudentDao studentDao = new StudentDao(context); Student student = new Student(); student.setId(1); student.setName("刘"); studentDao.add(student); Log.i(TAG, "添加成功!"); } }
在 </activity>外面 ,</application>里面加入这行 <service android:name=".StudentService" /> //包名已经在前面设置了,所以可以直接写
3,然后就是在activity添加按钮事件,创建按钮等一系列都省略了
代码如下
add = (Button) findViewById(R.id.add); add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, StudentService.class); Toast.makeText(MainActivity.this, "已经成功添加了数据!", Toast.LENGTH_LONG).show(); startService(intent); Log.i(TAG, "成功添加了"); } });
然后就完成了
版权声明:本文为博主原创文章,未经博主允许不得转载。