最近在学android,看着网上的例子,模仿写了一个,简单的实现了android的增删改查以及通知栏和定时任务
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/background"
tools:context="com.example.jhl.carinsurance.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/ii1"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="姓 名"
android:textColorHint="#cea4a4"
android:id="@+id/e1"
android:textColor="#FFFFFFFF"
android:gravity="center"
android:textSize="16sp"
android:inputType="textPersonName"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="性别"
android:textColorHint="#cea4a4"
android:textColor="#FFFFFFFF"
android:gravity="center"
android:textSize="16sp"
android:id="@+id/e2"
android:inputType="text"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="车险日期"
android:textColorHint="#cea4a4"
android:textColor="#FFFFFFFF"
android:id="@+id/e3"
android:textSize="16sp"
android:gravity="center"
android:inputType="date"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="手机号码"
android:textColorHint="#cea4a4"
android:textColor="#FFFFFFFF"
android:gravity="center"
android:id="@+id/e4"
android:textSize="16sp"
android:inputType="number"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="add"
android:id="@+id/i1"
android:src="@android:drawable/ic_input_add"
/>
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/l1"
android:layout_below="@id/ii1">
</ListView>
</RelativeLayout>
listview_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="蒋浩林"
android:textColor="#FFFF0000"
android:layout_weight="2"
android:textSize="16sp"
android:gravity="center"
android:id="@+id/t1"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"
android:textColor="#FFFF0000"
android:layout_weight="2"
android:textSize="16sp"
android:gravity="center"
android:id="@+id/t2"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="20170622"
android:textColor="#FFFF0000"
android:layout_weight="2"
android:textSize="16sp"
android:gravity="center"
android:inputType="date"
android:id="@+id/t3"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="18256070231"
android:textColor="#FFFF0000"
android:gravity="center"
android:layout_weight="2"
android:textSize="16sp"
android:inputType="number"
android:id="@+id/t4"/>
<ImageView
android:layout_width="22dp"
android:layout_height="22dp"
android:id="@+id/update"
android:layout_weight="1"
android:src="@android:drawable/ic_menu_edit"/>
<ImageView
android:layout_width="22dp"
android:layout_height="22dp"
android:id="@+id/delete"
android:src="@android:drawable/ic_menu_delete"/>
</LinearLayout>
创建数据库操作类
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by jhl on 2017/6/22.
*/
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context){
super(context,"carxian.db",null,2);
}
public void onCreate(SQLiteDatabase db){
System.out.println("onCreate");
db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(30),sex VARCHAR(10),phonenumber VARCHAR(20),istongzhi VARCHAR(2),dqsj date)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
System.out.println("onUpgrade");
}
}
bean实例
package com.example.jhl.carinsurance.bean;
import java.io.Serializable;
import java.util.Date;
/**
* Created by jhl on 2017/6/22.
*/
public class Account implements Serializable {
private Long id;
private String name;//姓名
private String sex;//性别
private String istongzhi;//通知标识 0未通知,1已通知
private String phoneNumber;//手机号
private String dqsj;//车险到期时间
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIstongzhi() {
return istongzhi;
}
public void setIstongzhi(String istongzhi) {
this.istongzhi = istongzhi;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getDqsj() {
return dqsj;
}
public void setDqsj(String dqsj) {
this.dqsj = dqsj;
}
public Account(Long id,String name,String sex,String phoneNumber,String istongzhi, String dqsj){
super();
this.id=id;
this.name=name;
this.sex=sex;
this.phoneNumber=phoneNumber;
this.istongzhi=istongzhi;
this.dqsj=dqsj;
}
public Account(String name,String sex,String phoneNumber,String istongzhi, String dqsj){
super();
this.name=name;
this.sex=sex;
this.phoneNumber=phoneNumber;
this.istongzhi=istongzhi;
this.dqsj=dqsj;
}
public Account(){
super();
}
public String toString(){
return "[姓名:"+name+",性别:"+sex+",手机号:"+phoneNumber+",到期时间:"+dqsj+"]";
}
}
数据库操作类
package com.example.jhl.carinsurance.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.jhl.carinsurance.bean.Account;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by jhl on 2017/6/22.
*/
public class AccountDao {
private MyHelper helper;
public AccountDao(Context context){
helper=new MyHelper(context);
}
//增加
public void insert(Account account){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name",account.getName());
values.put("sex",account.getSex());
values.put("phonenumber",account.getPhoneNumber());
values.put("istongzhi",account.getIstongzhi());
values.put("dqsj",account.getDqsj().toString());
long id=db.insert("account",null,values);
account.setId(id);
db.close();
}
//删除
public int delete(long id){
SQLiteDatabase db=helper.getWritableDatabase();
int count=db.delete("account","_id=?",new String[]{id+""});
db.close();
return count;
}
//修改
public int update(Account account){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name",account.getName());
values.put("sex",account.getSex());
values.put("phonenumber",account.getPhoneNumber());
values.put("istongzhi",account.getIstongzhi());
values.put("dqsj",account.getDqsj().toString());
int count=db.update("account",values,"_id=?",new String[]{account.getId()+""});
db.close();
return count;
}
//查询
public List<Account> queryAll(){
SQLiteDatabase db;
db = helper.getWritableDatabase();
Cursor c=db.query("account",null,null,null,null,null,"dqsj DESC");
List<Account> list=new ArrayList<Account>();
while (c.moveToNext()){
long id = c.getLong(c.getColumnIndex("_id"));
String name = c.getString(1);
String sex = c.getString(2);
String phonenumber = c.getString(3);
String istongzhi = c.getString(4);
String dqsj = c.getString(5);
list.add(new Account(id,name,sex,phonenumber,istongzhi,dqsj));
}
c.close();
db.close();
return list;
}
}
业务逻辑处理
package com.example.jhl.carinsurance;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.jhl.carinsurance.bean.Account;
import com.example.jhl.carinsurance.dao.AccountDao;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by jhl on 2017/6/22.
*/
public class CarInsuranceActivity extends Activity {
private List<Account> list;
private AccountDao dao;
private EditText e1;
private EditText e2;
private EditText e3;
private EditText e4;
private MyAdapter adapter;
private ListView lv;
private static int id = 100;
Handler handler=new Handler();
//定时任务
Runnable runnable=new Runnable() {
@Override
public void run() {
//要做的事情
findDqcl();
handler.postDelayed(this, 3600000);//每一个小时执行一次
}
};
private Notification mNotification;
private NotificationManager mNotificationManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//取消标题栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
dao = new AccountDao(this);
list=dao.queryAll();
adapter = new MyAdapter();
lv.setAdapter(adapter);
handler.postDelayed(runnable, 3600000);
}
//查询还有半个月就到期的驾驶人
public void findDqcl() {
for(Account accountList:list){
try {
String dqsjStr = accountList.getDqsj();
Long nowTime = new Date().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
long dqsjTime = sdf.parse(dqsjStr).getTime();
long sjc = dqsjTime - nowTime;
if(sjc >=0 && sjc <= 1296000000 && accountList.getIstongzhi().equals("0")){//1296000
tongZhi(accountList);
accountList.setIstongzhi("1");
dao.update(accountList);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//显示通知栏
public void tongZhi(Account account){
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String sexStr = "";
if(account.getSex().indexOf("男")!=-1){
sexStr = "先生";
}else{
sexStr = "女士";
}
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + account.getPhoneNumber()));//跳转到拨号界面,同时传递电话号码
/**
*
* pendingIntent:封装了Intent的预意图,表示
* 动作还没有发生,但是会一直保留着这个动作
* context 上下文
* requestCode:请求码
* intent :跳转意图
* Flag:标记
*/
PendingIntent pendingIntent =
PendingIntent.getActivity(this, id, dialIntent, PendingIntent.FLAG_ONE_SHOT);
mNotification = new NotificationCompat.Builder(this)
// 设置小图标
.setSmallIcon(R.mipmap.timg)
// .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
// 设置标题
.setContentTitle(account.getName()+sexStr+"的保险还有15天就到期啦")
// 设置内容
.setContentText("到期时间:"+account.getDqsj()+" 电话:"+account.getPhoneNumber()+" 点击拨打电话吧!")
// 设置Notification提示铃声为系统默认铃声
.setSound(
RingtoneManager.getActualDefaultRingtoneUri(
getBaseContext(),
RingtoneManager.TYPE_NOTIFICATION))
// 点击Notification的时候使它自动消失
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(id++, mNotification);
}
private void initView(){
lv = (ListView) findViewById(R.id.l1);
e1 = (EditText) findViewById(R.id.e1);
e2 = (EditText) findViewById(R.id.e2);
e3 = (EditText) findViewById(R.id.e3);
e4 = (EditText) findViewById(R.id.e4);
lv.setOnItemClickListener(new MyOnItemClickListener());
}
public void add(View v) {
String name = e1.getText().toString().trim();
String sex = e2.getText().toString().trim();
String dqsj = e3.getText().toString().trim();
String phoneNumber = e4.getText().toString().trim();
if(name.equals("")||sex.equals("")||dqsj.equals("")||phoneNumber.equals("")){
Toast.makeText(getApplicationContext(),"内容不能为空!",Toast.LENGTH_SHORT).show();
return;
}
Account a = new Account(name, sex,phoneNumber,"0",dqsj);
dao.insert(a);
list.add(a);
adapter.notifyDataSetChanged();
lv.setSelection(lv.getCount() - 1);
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
}
private class MyAdapter extends BaseAdapter {
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final View item = convertView != null ? convertView : View.inflate(
getApplicationContext(), R.layout.listview_item, null
);
EditText t1 = (EditText) item.findViewById(R.id.t1);
EditText t2 = (EditText) item.findViewById(R.id.t2);
EditText t3 = (EditText) item.findViewById(R.id.t3);
EditText t4 = (EditText) item.findViewById(R.id.t4);
final Account a = list.get(position);
t1.setText(a.getName());
t2.setText(a.getSex());
t3.setText(a.getDqsj());
t4.setText(a.getPhoneNumber());
ImageView delete = (ImageView) item.findViewById(R.id.delete);
ImageView update = (ImageView) item.findViewById(R.id.update);
update.setOnClickListener(new View.OnClickListener() {
EditText t1 = (EditText) item.findViewById(R.id.t1);
EditText t2 = (EditText) item.findViewById(R.id.t2);
EditText t3 = (EditText) item.findViewById(R.id.t3);
EditText t4 = (EditText) item.findViewById(R.id.t4);
public void onClick(View v) {
a.setName(t1.getText().toString());
a.setSex(t2.getText().toString());
a.setDqsj(t3.getText().toString());
a.setPhoneNumber(t4.getText().toString());
notifyDataSetChanged();
int count = dao.update(a);
if(count>0){
Toast.makeText(getApplicationContext(),"修改成功!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"修改失败!",Toast.LENGTH_SHORT).show();
}
}
});
delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final DialogInterface.OnClickListener listener = new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(a);
int count = dao.delete(a.getId());
if(count>0){
Toast.makeText(getApplicationContext(),"删除成功!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"删除失败!",Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(CarInsuranceActivity.this);
builder.setTitle("确定要删除吗?");
builder.setPositiveButton("确定", listener);
builder.setNegativeButton("取消", null);
builder.show();
}
});
return item;
}
}
private class MyOnItemClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Account a = (Account)parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),a.toString(),Toast.LENGTH_SHORT).show();
}
}
}