Android 下实现程序关闭后监听取消
2010-03-04 05:15:00 来源:WEB开发网StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] msg = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage currMsg : msg) {
sb.append("From:");
sb.append(currMsg.getDisplayOriginatingAddress());
sb.append(" Message:");
sb.append(currMsg.getDisplayMessageBody());
}
}
Intent i = new Intent(SvrId);
i.putExtra("PARAM", sb.toString());
sendBroadcast(i);
}
}
}
}
可以看到,前文中接收短信的代码被原封不动的复制到服务的代码内,唯一不同的就是服务中多了sendBroadcast()
二、修改BroadcastReceiver
package com.demo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class MessageReceiver extends BroadcastReceiver {
public static final String SvrId = "RARNU.SERVICE.DEMO";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().toString().equals(SvrId)) {
Bundle bund = intent.getExtras();
String strParam = "";
if (bund != null) {
strParam = bund.getString("PARAM");
}
Intent i = new Intent(context, MsgListen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(context, strParam, Toast.LENGTH_SHORT).show();
context.startActivity(i);
}
}
}
收短信的代码被移到服务中了,那么BroadcastReceive自然也不再需要那段代码,直接从Extras中取得服务传来的字符串即可。
更多精彩
赞助商链接