您的位置:首页 > 数据库

数据库_黑名单练习_完善服务广播

2016-06-12 11:20 330 查看
准备需要封装的类

数据库

package com.hanqi.xiangmu.hei2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
* Created by Administrator on 2016/6/12.
*/
public class dbhelp extends SQLiteOpenHelper{
public dbhelp(Context context) {
super(context, "t_blacklist",null,1);
}

@Override
public void onCreate(SQLiteDatabase db) {
String sql="CREATE TABLE  t_blacklist (\n" +
"\"_id\"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
"\"phonenumber\"  VARCHAR(20),\n" +
" name VARCHAR(20)\n" +
";\n";
db.execSQL(sql);

Log.e("TAG", "建表成功");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}


装载数据的实体类

package com.hanqi.xiangmu.hei2;

/**
* Created by Administrator on 2016/6/11.
*/
public class xinxi {
private String phonenumber;
private int id;
private String name;

public xinxi(String name, int id, String phonenumber) {
this.name = name;
this.id = id;
this.phonenumber = phonenumber;
}
public xinxi(String name,  String phonenumber) {
this.name = name;
this.phonenumber = phonenumber;
}

public xinxi( String phonenumber) {

this.phonenumber = phonenumber;
}
public xinxi( ) {

}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhonenumber() {
return phonenumber;
}

public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
}


装载数据库增删改查方法的方法类

package com.hanqi.xiangmu.hei2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hanqi.xiangmu.heimingdan.DBHelper;

import java.util.ArrayList;

/**
* Created by Administrator on 2016/6/12.
*/
public class xinxiDAO {
private Context context;
//private  DBHelper  sd;
private final String TABLENAME="t_blacklist";

//获得context;
public xinxiDAO(Context context){
this.context=context;
//  sd=new DBHelper(context);
}

//增
//传入参数
public long zeng(xinxi xx){
long rtn=0;
SQLiteDatabase sd=new DBHelper(context).getWritableDatabase();
//连接数据库
//执行insert语句
//insert into t_phonenumber (phone_number) values (ph)
ContentValues cv=new ContentValues();
cv.put("phonenumber",xx.getPhonenumber());
cv.put("name",xx.getName());

rtn= sd.insert(TABLENAME,null,cv);

sd.close();
return  rtn;
}

//删
public int shan(xinxi xx){
int rnt=0;
//delete from t_phonenumber where _id=?
SQLiteDatabase sd=new DBHelper(context).getReadableDatabase();

rnt=  sd.delete(TABLENAME, "_id=?", new String[]{xx.getId() + ""});

sd.close();
return rnt;
}
//改
public int gai(xinxi xx){
int rnt=0;
SQLiteDatabase sd=new DBHelper(context).getReadableDatabase();

// update t_phonenumber set phone_number = ? where _id=?

ContentValues cv = new ContentValues();
cv.put("phonenumber",xx.getPhonenumber());
cv.put("name",xx.getName());

rnt=  sd.update(TABLENAME, cv, "_id=?", new String[]{xx.getId() + ""});
sd.close();
return  rnt;
}

//查
public ArrayList<xinxi> getall(){
ArrayList<xinxi> blacks=new ArrayList<>();

SQLiteDatabase sd=new DBHelper(context).getReadableDatabase();

//selete * from t_blacklist

//查询之后得到游标结果集
Cursor cursor= sd.query(TABLENAME, null, null, null, null, null, "_id desc");

//遍历结果集
//把数据转成实体类的实例
while (cursor.moveToNext()){
String s1=cursor.getString(1);
String s2=cursor.getString(2);
int i=cursor.getInt(0);
//放id
xinxi b=new xinxi(s2,i,s1);
//2.把实例放在集合里
blacks.add(b);
}
cursor.close();
sd.close();
return  blacks;

}
public ArrayList<xinxi> cha(xinxi xx){
ArrayList<xinxi> blacks=new ArrayList<>();

SQLiteDatabase sd=new DBHelper(context).getReadableDatabase();

String s=" 1=1 ";
if(xx.getName().length()>0){
s+=" and name like '%"+xx.getName()+"%' ";
}
if(xx.getPhonenumber().length()>0){
s+=" and phonenumber like '%"+xx.getPhonenumber()+"%'";
}

//selete * from t_blacklist

//查询之后得到游标结果集
Cursor cursor= sd.query(TABLENAME, null, s, null, null, null, "_id desc");

//遍历结果集
//把数据转成实体类的实例
while (cursor.moveToNext()){
String s1=cursor.getString(1);
String s2=cursor.getString(2);
xinxi b=new xinxi(s2,s1);
//2.把实例放在集合里
blacks.add(b);
}
cursor.close();
sd.close();
return  blacks;

}
}


几个简单的视图文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.hanqi.xiangmu.hei2">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入查询内容"
android:id="@+id/at"
android:completionHint="1"
android:completionThreshold="1"/>
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/lv"></ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加"
android:onClick="b1"
/>

</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".hei2.h2">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入姓名"
android:id="@+id/et1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入号码"
android:id="@+id/et2"
android:inputType="number"/>

</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_weight="1"
android:hint="111"
android:id="@+id/tv1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_weight="3"
android:hint="222"
android:id="@+id/tv2"/></LinearLayout>
</LinearLayout>


java主代码

package com.hanqi.xiangmu.hei2;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hanqi.xiangmu.R;

import java.util.ArrayList;

public class h2 extends AppCompatActivity {
ArrayList<xinxi> al=new ArrayList<>();
// ArrayList<xinxi> al2=new ArrayList<>();
ListView lv;
xinxiDAO xd=new xinxiDAO(h2.this);
base b=new base();
int index;
AutoCompleteTextView at;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hei2);
lv=(ListView)findViewById(R.id.lv);
al=xd.getall();
lv.setAdapter(b);
lv.setOnCreateContextMenuListener(this);
//at=(AutoCompleteTextView)findViewById(R.id.at);

}
class base extends BaseAdapter{
@Override
public int getCount() {
return al.size();
}

@Override
public Object getItem(int position) {
return al.get(position);
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
xinxi xx=al.get(position);
if (convertView==null){
convertView=View.inflate(h2.this,R.layout.h1,null);
}

TextView tv1=(TextView)convertView.findViewById(R.id.tv1);
TextView tv2=(TextView)convertView.findViewById(R.id.tv2);
tv1.setText(xx.getName());
tv2.setText(xx.getPhonenumber());
return convertView;
}
}
public void b1(View view){
final View view1=View.inflate(h2.this,R.layout.h2,null);
AlertDialog alertDialog=new AlertDialog.Builder(h2.this)
.setTitle("输入黑名单内容")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

EditText et1 = (EditText) view1.findViewById(R.id.et1);
EditText et2 = (EditText) view1.findViewById(R.id.et2);
String s = et1.getText().toString();
String ss = et2.getText().toString();
if (s.length() > 0 && ss.length() > 0) {
xinxi  xx = new xinxi(s, ss);
long l = xd.zeng(xx);

if (l > 0) {
Toast.makeText(h2.this, "保存成功", Toast.LENGTH_SHORT).show();
al = xd.getall();
b.notifyDataSetChanged();
Toast.makeText(h2.this, xx.getId()+"", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(h2.this, "保存失败", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(h2.this, "请输入内容", Toast.LENGTH_SHORT).show();
}
}
}
)
.setNegativeButton("取消",null)
.setCancelable(false)
.setView(view1)
.show();
}

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 1, 1, "修改");
menu.add(0,2,2,"删除");

//获取长按的数据信息
//获得菜单信息
AdapterView.AdapterContextMenuInfo acm=(AdapterView.AdapterContextMenuInfo)menuInfo;
index = acm.position;

}

//响应菜单点击的回调方法
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case 1:
//修改
final View view1=View.inflate(h2.this, R.layout.h2, null);
new AlertDialog.Builder(this)
.setTitle("输入修改内容")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

EditText et1 = (EditText) view1.findViewById(R.id.et1);
EditText et2 = (EditText) view1.findViewById(R.id.et2);
String s = et1.getText().toString();
String ss = et2.getText().toString();
Toast.makeText(h2.this,al.get(index).getId()+ "", Toast.LENGTH_SHORT).show();
if(ss.length()==0){
Toast.makeText(h2.this, "至少输入电话号码", Toast.LENGTH_SHORT).show();
return;
}
if (s.length() > 0 && ss.length() > 0) {
long l = xd.gai(new xinxi(s,al.get(index).getId(),  ss));

if (l > 0) {
Toast.makeText(h2.this, "修改成功", Toast.LENGTH_SHORT).show();
al = xd.getall();
b.notifyDataSetChanged();
} else {
Toast.makeText(h2.this, "保存失败", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(h2.this, "请输入内容", Toast.LENGTH_SHORT).show();
return;
}
}
}
)
.setNegativeButton("取消",null)
.setCancelable(false)
.setView(view1)
.show();
break;
case 2:
//删除
new  AlertDialog.Builder(this)
.setTitle("是否删除")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
xd.shan(al.get(index));

al=xd.getall();
//al.remove(index);
b.notifyDataSetChanged();

}
})
.setNegativeButton("取消",null)
.show();

break;
}

return super.onContextItemSelected(item);

}

//    class base2 extends BaseAdapter{
//        @Override
//        public int getCount() {
//            return al2.size();
//        }
//
//        @Override
//        public Object getItem(int position) {
//            return al2.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return 0;
//        }
//
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            xinxi xx=al2.get(position);
//            if (convertView==null){
//                convertView=View.inflate(h2.this,R.layout.h1,null);
//            }
//
//            TextView tv1=(TextView)convertView.findViewById(R.id.tv1);
//            TextView tv2=(TextView)convertView.findViewById(R.id.tv2);
//            tv1.setText(xx.getName());
//            tv2.setText(xx.getPhonenumber());
//            return convertView;
//        }
//  }
}


权限及广播代码

<!-- 开机启动 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- 拨打挂断电话 -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!-- 读取电话状态 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<!-- 接收短信广播 -->
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<!--读取短信-->
<uses-permission android:name="android.permission.READ_SMS"/>

<receiver
android:name=".hei2.MyReceiver_Sms"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<receiver
android:name=".hei2.MyReceiver_phone"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>


开机自启动广播打开电话服务

public class MyReceiver_phone extends BroadcastReceiver {
public MyReceiver_phone() {
}

@Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MyService.class);
context.startService(intent1);
}
}


黑名单服务!!(无法执行挂断命令)

package com.hanqi.xiangmu.hei2;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.util.ArrayList;

public class MyService extends Service {

xinxiDAO xx = new xinxiDAO(MyService.this);
ArrayList<xinxi> al = new ArrayList<>();
ArrayList<String> aln = new ArrayList<>();

private TelephonyManager telephonyManager;
public MyService() {
Log.e("TAG", "黑名单电话服务启动");
new Thread(){
@Override
public void run() {
super.run();
while (true){
try {
Thread.sleep(60000);
al = xx.getall();
for (xinxi x : al) {
aln.add(x.getPhonenumber());
}
}catch (Exception e){

}
}
}
}.start();

}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private PhoneStateListener phoneStateListener=new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state){
case TelephonyManager.CALL_STATE_IDLE :
Log.e("TAG","空闲状态");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.e("TAG","接通状态");
Log.e("TAG",incomingNumber+"??");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.e("TAG","响铃状态");
Log.e("TAG",incomingNumber);
//判断电话号码是否在黑名单中
if (aln.size()!=0&&aln.contains(incomingNumber)){
Log.e("TAG","准备拦截电话"+incomingNumber);
}
break;
}
}
};

@Override
public void onCreate() {

telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}

@Override
public void onDestroy() {
super.onDestroy();
telephonyManager.listen(phoneStateListener,PhoneStateListener.LISTEN_NONE);
}
}


短信广播

package com.hanqi.xiangmu.hei2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;

public class MyReceiver_Sms extends BroadcastReceiver {

ArrayList<xinxi> al = new ArrayList<>();
ArrayList<String> aln = new ArrayList<>();

public MyReceiver_Sms() {
Log.e("TAG","黑名单短信服务启动");
}

@Override
public void onReceive(Context context, Intent intent) {

final xinxiDAO xx = new xinxiDAO(context);

new Thread(){
@Override
public void run() {
super.run();
while (true){
try {
Thread.sleep(60000);
al = xx.getall();
for (xinxi x : al) {
aln.add(x.getPhonenumber());
}
}catch (Exception e){

}
}
}
}.start();
if (aln.size() != 0) {
Bundle bundle = intent.getExtras();

Object[] objects = (Object[]) bundle.get("pdus");

//得到对象
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) objects[0]);

//得到电话
String number = smsMessage.getOriginatingAddress();
String content = smsMessage.getMessageBody();
Log.e("TAG", "短信电话" + number);
Log.e("TAG", "内容" + content);

//连接数据库,获取黑名单电话

//进行比对,如果匹配就拦截
if (aln.contains(number)) {
abortBroadcast();
Toast.makeText(context, "拦截了" + number + "的短信", Toast.LENGTH_SHORT).show();
}
}
}
}


自动文本未完成
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: