我正在使用Broadcast Receiver接收短信。它工作正常。現在我想使用服務從收件箱中讀取短信(由廣播接收器接收)。如何使用服務讀取短信
我想使用SERVICE從收件箱中檢索短信。 SMS retreival必須在後臺進行,而不是在主線程中。不應使用任何活動。 //廣播接收機接收SMS和經由意圖啓動服務 公共類SMSReceiver延伸的BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] message = null;
String str = "";
if(bundle != null){
Object[] pdus = (Object[])bundle.get("pdus");
message = new SmsMessage[pdus.length];
for(int i = 0; i<message.length; i++){
message[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "New SMS from cloudy contacts " + message[i].getOriginatingAddress();
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(context,MyService.class);
context.startService(intent1);
}
}
}
役 公共類爲MyService延伸服務{ ReadSMS readSMS;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate(Bundle savedInstanceState){
Log.d("Service","inside onCreate of service");
}
public void onDestroy(){
Log.d("Service", "destroyed");
}
public void onStart(){
Log.d("Service","starting service to read sms from inbox");
Toast.makeText(this,"Reading sms from inbox",Toast.LENGTH_LONG).show();
readSMS = new ReadSMS();
ArrayList list = readSMS.readSms("inbox");
}
public class ReadSMS{
public ArrayList readSms(String inbox){
ArrayList sms = new ArrayList();
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uri, new String[]{"_id","address","date","body"},null,null,null);
cursor.moveToLast();
String address = cursor.getString(1);
String body = cursor.getString(3);
sms.add(address+" "+body);
return sms;
}
}
}
請問您可以加些代碼 – 2013-04-06 06:38:37