最近,小弟在寫一個攔截短信的android 程序,在開啟攔截服務這個地方被卡了好幾天了,
換了好幾種思路,最後參考一種網上的思路用了AsyncTask這種思路。
但是運行程序的時候報錯,但是不太清楚哪裡出錯了,求大神幫看一看服務的這個包。
public class MsgService extends Service{
private boolean D=true;
private ReceiveMessage mReceiver;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
if(D){
Log.i("msgservice"," onCreate()");
}
//注冊動態廣播
mReceiver=new ReceiveMessage();
IntentFilter filter=new IntentFilter();
filter.setPriority(Integer.MAX_VALUE);
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mReceiver, filter);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(D){
Log.i("msgservice","onStartCommand");
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if(D){
Log.i("msgservice","onDestroy() ");
}
//取消廣播接收者
unregisterReceiver(mReceiver);
mReceiver=null;
super.onDestroy();
}
class ReceiveMessage extends BroadcastReceiver {
private String address;
private String fullMessage;
private MyDatabaseHelper dbHelper;
// 當接收到短息時被觸發
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
// 判斷是否有數據
if (bundle != null) {
// 通過pdus可以獲得接收到的所有短信消息
Object[] pdus = (Object[]) bundle.get("pdus");
// 構建短息對象array,並依據收到的對象長度來創建array的大小
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
address = messages[0].getOriginatingAddress();//獲取發送方號碼
fullMessage = "";
for (SmsMessage message : messages) {
fullMessage +=message.getMessageBody();//獲取短信內容
}
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(Void result) {
if(fullMessage.startsWith("Test")||fullMessage.endsWith("Test"))//發現短信,攔截,並且存入數據庫
{
abortBroadcast(); // 取消廣播(這行代碼將會讓系統接受短信程序收不到短息)
//入庫要從新寫,用AsyncTask
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... params) {
//把陌生人短信存儲在數據庫表裡
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("phonenumber",address);
values.put("content",fullMessage);
db.insert("TEXT", null, values);
return null;
}
}.execute();
}
super.onPostExecute(result);
}
}.execute();
}
}
}
}
在發送一個攔截開頭為Test的短息的時候,報錯如圖:
日志裡caused by原因是空指針,程序97行,空指針好解決,斷點看看怎麼空了