我正在开发一个Android应用程序,我必须检查传入的短信是否包含我的原始文件夹文本文件中定义的单词。 我将文本文件命名为关键字,它包含40个以逗号分隔的关键字。 现在我想要的是,当新的短信出现时,如果它包含我的文本文件中定义的关键字,那么SMS将保存在列表视图中。我设法使用硬编码字符串,但我无法通过从文本文件中读取关键字来做到这一点。 这是我在广播接收器中的实现。
if (msgBody.contains(readTxt()) && !contactExists(context, msg_from)) {
screenMessage(context, msg_from, msg_from, msgBody, msgDate);
}
和readtTxt在这里定义
private String readTxt(){
InputStream inputStream = context.getResources().openRawResource(R.raw.keywords);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
但是当一个短信来了,如果它包含在文本文件中指定的关键字,该应用程序将被强制关闭并显示
NullPointerException,println需要一条消息
我被困住了,不知道该怎么办,因为该消息也没有保存,应用程序也强行关闭。
这是我的LOGCAT
04-18 14:53:41.061: E/AndroidRuntime(8335): FATAL EXCEPTION: main
04-18 14:53:41.061: E/AndroidRuntime(8335): Process: com.tech.tabs, PID:8335
04-18 14:53:41.061: E/AndroidRuntime(8335): java.lang.RuntimeException: Unable to start receiver com.tech.spam.SmsReceived: java.lang.NullPointerException: println needs a message
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2675)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.app.ActivityThread.access$1800(ActivityThread.java:175)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.os.Handler.dispatchMessage(Handler.java:102)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.os.Looper.loop(Looper.java:146)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.app.ActivityThread.main(ActivityThread.java:5602)
04-18 14:53:41.061: E/AndroidRuntime(8335): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 14:53:41.061: E/AndroidRuntime(8335): at java.lang.reflect.Method.invoke(Method.java:515)
04-18 14:53:41.061: E/AndroidRuntime(8335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
04-18 14:53:41.061: E/AndroidRuntime(8335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
04-18 14:53:41.061: E/AndroidRuntime(8335): at dalvik.system.NativeStart.main(Native Method)
04-18 14:53:41.061: E/AndroidRuntime(8335): Caused by: java.lang.NullPointerException: println needs a message
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.util.Log.println_native(Native Method)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.util.Log.i(Log.java:195)
04-18 14:53:41.061: E/AndroidRuntime(8335): at com.tech.spam.SmsReceived.onReceive(SmsReceived.java:156)
04-18 14:53:41.061: E/AndroidRuntime(8335): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2660)
04-18 14:53:50.981: D/ProgressBar(8610): updateDrawableBounds: left = 0
public class SmsReceived extends BroadcastReceiver {
Context context;
ArrayList<String> keywordslist = new ArrayList<String>();
@SuppressLint({ "DefaultLocale", "InlinedApi" })
@Override
public void onReceive(Context context, Intent intent) {
LinkedHashMap<String, String> contactNumber = new LinkedHashMap<String, String>();
DBkeyword screenedKeywordDB = new DBkeyword(context);
SQLiteDatabase db = screenedKeywordDB.getWritableDatabase();
Cursor cur1 = db.rawQuery(Constants.readScreenedKeywords, null);
cur1.moveToFirst();
while (!cur1.isAfterLast())
{
keywordslist.add(cur1.getString(0));
cur1.moveToNext();
}
db.close();
DBTable dbtable = new DBTable(context);
SQLiteDatabase dbrsn = dbtable.getReadableDatabase();
Cursor cur = dbrsn.rawQuery(Constants.readScreenedNumbers, null);
cur.moveToFirst();
while (!cur.isAfterLast())
{
contactNumber.put(cur.getString(0), cur.getString(1));
cur.moveToNext();
}
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null) {
try {
boolean keywordPresent = false;
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
msg_from = Utilities.extractNumbers(msg_from);
Long dateLong = msgs[i].getTimestampMillis();
String msgDate = dateLong.toString();
ContentValues values = new ContentValues();
values.put("address", msg_from);
values.put("date", System.currentTimeMillis()+"");
values.put("read", "1");
values.put("type", "1");
values.put("body",msgBody);
Uri uri = Uri.parse("content://sms/");
context.getContentResolver().insert(uri,values);
if (contactExists(context, msg_from))
{
/*Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));*/
NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
notify.setSmallIcon(R.drawable.iconapp);
notify.setContentTitle(msg_from);
notify.setContentText(msgBody);
notify.setAutoCancel(true);
notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notify.setLights(Color.GREEN, 2000, 2000);
notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
notificationIntent.setType("vnd.android-dir/mms-sms");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
notify.setContentIntent(intentt);
//notify.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 268435456));
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notify.build());
}
if (msgBody.contains(readTxt()) && !contactExists(context, msg_from))
{
screenMessage(context, msg_from, msg_from, msgBody, msgDate);
}
if (keywordslist != null) {
for (int i1 = 0; i1 < keywordslist.size(); i1++) {
String keyword = keywordslist.get(i1);
if (msgBody.toUpperCase().contains(keyword.toUpperCase()) && !contactExists(context, msg_from)) {
keywordPresent = true;
screenMessage(context, msg_from, msg_from, msgBody, msgDate);
break;
}
}
}
if (!keywordPresent) {
for (String key : contactNumber.keySet()) {
String msgSender = contactNumber.get(key);
String extractedContact = Utilities.extractNumbers(key);
if (msg_from.equalsIgnoreCase(extractedContact)) {
screenMessage(context, msg_from, msgSender, msgBody, msgDate);
break;
}
}
}
dbrsn.close();
}
} catch (Exception e) {
Log.i("Exception caught", e.getMessage());
}
}
}
}
private String readTxt(){
InputStream inputStream = context.getResources().openRawResource(R.raw.keywords);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
}
catch (IOException e) {
String err = (e.getMessage()==null)?"SD Card failed":e.getMessage();
Log.e("sdcard-err2:",err);
}
return byteArrayOutputStream.toString();
}
public boolean contactExists(Context context, String number) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
}
finally
{
if (cur != null)
cur.close();
}
return false;
}
public void screenMessage(Context context, String msg_from, String msgSender,
String msgBody, String msgDate) {
DBsms smsdb = new DBsms(context);
SQLiteDatabase dbw = smsdb.getWritableDatabase();
String query_insertSMS = "insert into " + "sms" + "(" + "contactnumber" + "," + "contactname" + "," + "message"
+ "," + "date" + ") values (\"" + msg_from.toString() + "\", \"" + msgSender + "\",\"" + msgBody
+ "\",\"" + msgDate + "\")";
dbw.execSQL(query_insertSMS);
smsdb.close();
dbw.close();
abortBroadcast();
}
}