我的应用商店中的用户有一个数字数据库。 我想收到一条仅来自这些号码的短信。 基本上我应该怎么做?
请帮助我。谢谢。
DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "PhoneNumber.db";
public static final String TABLE_NAME = "number_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NUMBER INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String number){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,number);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public ArrayList getAllrecord(){
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from admin", null);
res.moveToFirst();
while (res.isAfterLast()== false){
array_list.add(res.getString(res.getColumnIndex("number")));
res.moveToNext();
}
return array_list;
}
ReceiveMessage:
public class ReceiveMessage extends BroadcastReceiver {
final SmsManager mysms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
Bundle mybundel = intent.getExtras();
try {
if(mybundel !=null){
final Object[] messageContent=(Object[])mybundel.get("pdus");
String smsMessageStr = "";
for (int i=0;i<messageContent.length;i++){
SmsMessage mynewsms = SmsMessage.createFromPdu((byte[]) messageContent[i]);
NewMessageNotification nome = new NewMessageNotification();
nome.notify(context,mynewsms.getDisplayOriginatingAddress(),mynewsms.getDisplayMessageBody(),i);
i++;
String smsBody = mynewsms.getMessageBody().toString();
String address = mynewsms.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();
//this will update the UI with message
SmsInbox inst = SmsInbox.instance();
inst.updateList(smsMessageStr);
}
}
catch (Exception ex){
}
}
smsInbox:
public class SmsInbox extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemClickListener {
private static SmsInbox inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static SmsInbox instance() {
return inst;
}
@Override
public void onStart() {
super.onStart();
inst = this;
}
DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_inbox);
smsListView = (ListView) findViewById(R.id.SmsList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://sms/inbox"), null, null,
null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddr = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + cursor.getString(indexAddr) +
"\n" + cursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (cursor.moveToNext());
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(false);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menuRight) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Home_page) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.not_pay) {
if (SmsInbox.this.drawer != null && SmsInbox.this.drawer.isDrawerOpen(GravityCompat.END)) {
SmsInbox.this.drawer.closeDrawer(GravityCompat.END);
} else {
Intent intent = new Intent(this, MainActivity.class);
SmsInbox.this.startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
} else if (id == R.id.date_pay) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.bill_sms) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.help_menu) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.for_us) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.exit_app) {
finish();
overridePendingTransition(0, 0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);
return true;
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
数据库表:
答案 0 :(得分:1)
为此,您需要创建公开BroadcastReceiver
来抓住IncomingSms
为此你需要在清单文件中添加权限
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
在清单文件中添加Receiver标记
<receiver android:name="com.androidexample.broadcastreceiver.IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
创建类IncomingSms.java
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
您需要将传入的短信号码与您的数据库进行匹配,使用SQLite查询,您可以在Google上轻松找到选择查询。
答案 1 :(得分:1)
您必须在DatabaseHelper.java中声明一个函数来检查数字是否存在。
public bool isExists(String Number)
有这样的查询:
Select count(*) from number_table where number = 'Number'
然后在接收器中添加这些代码
String smsBody = mynewsms.getMessageBody().toString();
String address = mynewsms.getOriginatingAddress();
if(dbHelper.isExists(address)){
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}