以下代码效果很好,但我认为它过于复杂。
SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsBroadcastReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
PublicPar.myContext=context;
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
MSms myMSms=new MSms();
Intent msgIntent = new Intent(context,SmsInternetServer.class);
HandleSMS.SetIntentOrGetFromIntent(msgIntent, myMSms, true);
context.startService(msgIntent);
}
}
}
}
SmsInternetServer.java
public class SmsInternetServer extends IntentService {
public SmsInternetServer() {
super("SmsInternetServer");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
HandleSMS.HandleReceivedSMS(intent);
}
}
所以我把两个java文件中的两个类合并成一个,是不是可以?是否有更简单的方法来简化代码?比如匿名课。
SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsBroadcastReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
PublicPar.myContext=context;
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
MSms myMSms=new MSms();
Intent msgIntent = new Intent(context,SmsInternetServer.class);
HandleSMS.SetIntentOrGetFromIntent(msgIntent, myMSms, true);
context.startService(msgIntent);
}
}
}
//inner class
class SmsInternetServer extends IntentService {
public SmsInternetServer() {
super("SmsInternetServer");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
HandleSMS.HandleReceivedSMS(intent);
}
}
}
答案 0 :(得分:2)
您可以在一个java文件中定义任意数量的类。仅限制就是每个文件可以有一个公共类。 在您的情况下,您也可以在SmsBroadcastReceiver之外定义SMSInternet服务器。没有必要将其定义为内部类