• 利用IntentService服务执行方法


    这里只说重要的代码

    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, "添加成功!");
    	}
    
    }
    


    2,然后要在AndroidManifest.xml文件中配置服务

    在 </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, "成功添加了");
    			}
    		});

    然后就完成了

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    CSS躬行记(9)——网格布局
    CSS躬行记(8)——裁剪和遮罩
    CSS躬行记(7)——合成
    CentOS 系统目录解析
    Linux 命令快捷键
    秒的精确度
    Oracle和mysql中装逼dual表的用途介绍
    mysql 的mgr集群
    ansible笔记
    cygwin
  • 原文地址:https://www.cnblogs.com/shipeng22022/p/4614051.html
Copyright © 2020-2023  润新知