• 利用Service服务执行方法


    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啦

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

  • 相关阅读:
    ThinkPHP5+Bootstrap的极速后台开发框架。
    window 下要运行php,需要编辑php环境变量
    Mui 底部导航切换
    chrome 监听touch类事件报错:无法被动侦听事件preventDefault
    HBuilder开发MUI web app溢出页面上下无法滚动问题
    D建立app项目(mui)
    宝塔linux面板,phpmyadmin进不去的处理方法
    mysql密码重置
    mysql5.6安装以及密码重置
    linux安装软件命令
  • 原文地址:https://www.cnblogs.com/shipeng22022/p/4614050.html
Copyright © 2020-2023  润新知