Java 信息=信息。替换(“CN”、“CN”、“CN”、“CO”);未按预期运行
我有一个应用程序,它可以收集wifi和手机数据使用情况,并通过SMS将其作为一个数据字符串发送-但是我需要一些帮助来修改它发送到正确格式的字符串 现在看来:Java 信息=信息。替换(“CN”、“CN”、“CN”、“CO”);未按预期运行,java,android,string,replace,format,Java,Android,String,Replace,Format,我有一个应用程序,它可以收集wifi和手机数据使用情况,并通过SMS将其作为一个数据字符串发送-但是我需要一些帮助来修改它发送到正确格式的字符串 现在看来: USI;1;3056090866;06/16/58/06/24/13;CN25.48,WN86.957;CN34.931,WN16.656 我希望它以以下方式发送:(第二个CN和WN更改为CO和WO) 如何做到这一点?我已尝试使用: info = info.replace("CN", "CN", "CN, "CO""); 及 但两者都没
USI;1;3056090866;06/16/58/06/24/13;CN25.48,WN86.957;CN34.931,WN16.656
我希望它以以下方式发送:(第二个CN和WN更改为CO和WO)
如何做到这一点?我已尝试使用:
info = info.replace("CN", "CN", "CN, "CO"");
及
但两者都没有给出预期的产出
附言
无论建议采用何种方法,都需要考虑这一串数据更改中的数值-但字母CN和WN(蜂窝网络和无线网络)保持不变-我只需要将输出中的第二个CN和WN更改为WO和CO
完整资料来源:
public class DataCountService extends Service {
String text = "USR;1";
String ERROR = Constants.PREFS_NAME;
private Timer timer = new Timer();
private long period;
private long delay_interval;
private Intent getIntent() {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Constants.TAG, "Logging Service Started");
// super.onStartCommand(intent, flags, startId);
Bundle extras = intent.getExtras();
if (intent == null) {
// Exit gracefully is service not started by intent
Log.d(Constants.TAG, "Error: Null Intent");
} else {
if (extras != null) {
text = extras.getString(Constants.DM_SMS_CONTENT);
// check for Enable or Disable Value - if set to enable
// check for Enable or Disable Value - if set to enable
if (extras.getString(Constants.DM_SMS_CONTENT).contains(
"//USR;1")) {
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
// get Wifi and Mobile traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.###");
String status = (settings.getString("status", "0"));
String tag = ";";
String mobileStr = nf.format(mobileBytes);
String totalStr = nf.format(totalBytes);
// get the MDN
TelephonyManager tm = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
// Extract the phone number from the TelephonyManager
// instance
String mdn = tm.getLine1Number();
// Insure MDN is 10 characters
if (mdn.length() < 10 || mdn == null)
mdn = "0000000000";
// Extract last 10 digits of MDN
if (mdn.length() > 10)
mdn = mdn.substring(mdn.length() - 10, mdn.length());
char data[] = mdn.toCharArray();
char digit;
for (int index = 0; index < mdn.length() - (mdn.length())
% 2; index += 2) {
digit = data[index];
data[index] = data[index + 1];
data[index + 1] = digit;
}
// get the date
SimpleDateFormat s = new SimpleDateFormat(
"hh/mm/ss/MM/dd/yy");
String DToDevice = s.format(new Date());
String info = String.format("USI%sCN%s,WN%s", tag + status
+ tag + mdn + tag + DToDevice + tag, mobileStr,
totalStr + settings.getString("last_month", "0"));
info = "USI" + info.replace("USI", "");
// send traffic info via sms & save the current time
SmsManager smsManager = SmsManager.getDefault();
if (Config.DEVELOPMENT) {
String shortCode = settings.getString(
Constants.PREFS_KEY_SHORT_CODE,
Constants.DEFAULT_SHORT_CODE);
smsManager.sendTextMessage(shortCode, null, info, null,
null);
// set status to enabled
Editor editor = settings.edit();
editor.putString("status", "1");
editor.commit();
editor.putLong("smstimestamp",
System.currentTimeMillis());
editor.commit();
} else {
SmsManager ackSMS = SmsManager.getDefault();
smsManager.sendTextMessage(
Constants.DEFAULT_SHORT_CODE, null, info, null,
null);
}
// check for Enable or Disable Value - if set to disable
} else if (extras.getString(Constants.DM_SMS_CONTENT).contains(
"//USR;0")) {
// set status to disabled
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
Editor editor = settings.edit();
editor.putString("status", "0");
editor.commit();
stopSelf();
// check for Enable or Disable Value - if set to any other
// character
}
}
}
return START_NOT_STICKY;
}
private Intent Intent() {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
if (Config.DEVELOPMENT) {
period = Constants.PERIOD;
delay_interval = Constants.DELAY_INTERVAL;
} else {
Bundle extras = getIntent().getExtras();
period = Constants.DEBUG_PERIOD;
delay_interval = Constants.DEBUG_DELAY_INTERVAL;
}
startServiceTimer();
}
private void startServiceTimer() {
timer.schedule(new TimerTask() {
public void run() {
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
if (settings.getString("status", "0").equals(1)) {
// get Wifi and Mobile traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.###");
String tag = ";";
String mobileStr = nf.format(mobileBytes);
String totalStr = nf.format(totalBytes);
String info = String.format("CO%s,WO%s", tag, mobileStr,
totalStr);
// save Network and Wifi data in sharedPreferences
SharedPreferences cnwn = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
Editor editor = cnwn.edit();
editor.putString("last_month", info);
editor.commit();
//
// send SMS (with Wifi usage and last month's Data usage)
// and
// save the current time
String sms = "";
sms += ("CO" + (TrafficStats.getMobileRxBytes() + TrafficStats
.getMobileTxBytes()) / 1000000);
sms += ("WO" + (TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes() - (TrafficStats
.getMobileRxBytes() + TrafficStats
.getMobileTxBytes())) / 1000000);
SmsManager smsManager = SmsManager.getDefault();
if (Config.DEVELOPMENT) {
String shortCode = settings.getString(
Constants.PREFS_KEY_SHORT_CODE,
Constants.DEFAULT_SHORT_CODE);
smsManager.sendTextMessage(shortCode, null,
sms + cnwn.getString("last_month", ""), null,
null);
editor.putLong("smstimestamp",
System.currentTimeMillis());
editor.commit();
} else {
SmsManager ackSMS = SmsManager.getDefault();
smsManager.sendTextMessage(
Constants.DEFAULT_SHORT_CODE, null,
sms + cnwn.getString("last_month", ""), null,
null);
}
}
}
}, delay_interval, period);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
}
请尝试此代码->
String str = "USI;1;3056090866;06/16/58/06/24/13;CN25.48,WN86.957;CN34.931,WN16.656";
StringBuilder b = new StringBuilder(str);
b.replace(str.lastIndexOf("CN") - 1, str.lastIndexOf("CN") + 2, "CO" );
b.replace(str.lastIndexOf("WN") - 1, str.lastIndexOf("WN") + 2, "WO" );
str = b.toString();
它会起作用的。Amani,我同意Vishal上面的答案会起作用——你只需要用你自己的数据替换他在顶部初始化的字符串str。然后通过他发布的后四行代码运行它
在这个阶段,我们都假设您的数据字符串只能包含“随机”部分中的数字,并且文本CN和WO正好出现两次。你在问题中的帖子暗示了这一点。如果它们可以更频繁地出现,此解决方案将始终替换最后出现的事件。如果它们不经常出现,此解决方案将抛出异常(即,它将崩溃)。此字符串的格式是否为常量?或者它可以随时间变化?它不是恒定的-它不断变化CN和WN标记值是恒定的,尽管(无线网络和蜂窝网络)唯一变化的值是数字字符串中的常量是什么?至少“;”是常数吗?我很乐意解释!字符串的工作方式是这样的USI每次都保持不变,1代表启用或禁用-3056090866是用户的电话号码,06/16/58/06/24/13是日期/时间,CN代表蜂窝网络,之后的数字是MB中使用的数据,WN代表无线网络和MB中使用的数据,第二个CN值(我希望从CN改为CO)是最近几个月的手机数据使用情况,第二个WN是最近几个月的无线数据使用情况)我现在编码的方式-它只显示WN和CN 2x,我需要它显示。。。嗯。。。中国。。。我。。。CO…看一看我最近发布的完整源代码-提到的字符串因设备而异,因为它的值不断变化,所以我想我需要一种稍微不同的方法,您建议的方法此方法不会替换第二个CN和WN值我也尝试过-StringBuilder b=new StringBuilder(); b.替换(sms.lastIndexOf(“CN”)-1,sms.lastIndexOf(“CN”)+2,“CO”);b.替换(sms.lastIndexOf(“WN”)-1,sms.lastIndexOf(“WN”)+2,“WO”);但是它也不会修改输出的最后两个值(帮助!):)这个答案在我看来是正确的。不要忘记您修改了
info
,所以请使用StringBuilder b=new-StringBuilder(info)
和info=b.toString()
。
public class DataCountService extends Service {
String text = "USR;1";
String ERROR = Constants.PREFS_NAME;
private Timer timer = new Timer();
private long period;
private long delay_interval;
private Intent getIntent() {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Constants.TAG, "Logging Service Started");
// super.onStartCommand(intent, flags, startId);
Bundle extras = intent.getExtras();
if (intent == null) {
// Exit gracefully is service not started by intent
Log.d(Constants.TAG, "Error: Null Intent");
} else {
if (extras != null) {
text = extras.getString(Constants.DM_SMS_CONTENT);
// check for Enable or Disable Value - if set to enable
// check for Enable or Disable Value - if set to enable
if (extras.getString(Constants.DM_SMS_CONTENT).contains(
"//USR;1")) {
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
// get Wifi and Mobile traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.###");
String status = (settings.getString("status", "0"));
String tag = ";";
String mobileStr = nf.format(mobileBytes);
String totalStr = nf.format(totalBytes);
// get the MDN
TelephonyManager tm = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
// Extract the phone number from the TelephonyManager
// instance
String mdn = tm.getLine1Number();
// Insure MDN is 10 characters
if (mdn.length() < 10 || mdn == null)
mdn = "0000000000";
// Extract last 10 digits of MDN
if (mdn.length() > 10)
mdn = mdn.substring(mdn.length() - 10, mdn.length());
char data[] = mdn.toCharArray();
char digit;
for (int index = 0; index < mdn.length() - (mdn.length())
% 2; index += 2) {
digit = data[index];
data[index] = data[index + 1];
data[index + 1] = digit;
}
// get the date
SimpleDateFormat s = new SimpleDateFormat(
"hh/mm/ss/MM/dd/yy");
String DToDevice = s.format(new Date());
String info = String.format("USI%sCN%s,WN%s", tag + status
+ tag + mdn + tag + DToDevice + tag, mobileStr,
totalStr + settings.getString("last_month", "0"));
info = "USI" + info.replace("USI", "");
// send traffic info via sms & save the current time
SmsManager smsManager = SmsManager.getDefault();
if (Config.DEVELOPMENT) {
String shortCode = settings.getString(
Constants.PREFS_KEY_SHORT_CODE,
Constants.DEFAULT_SHORT_CODE);
smsManager.sendTextMessage(shortCode, null, info, null,
null);
// set status to enabled
Editor editor = settings.edit();
editor.putString("status", "1");
editor.commit();
editor.putLong("smstimestamp",
System.currentTimeMillis());
editor.commit();
} else {
SmsManager ackSMS = SmsManager.getDefault();
smsManager.sendTextMessage(
Constants.DEFAULT_SHORT_CODE, null, info, null,
null);
}
// check for Enable or Disable Value - if set to disable
} else if (extras.getString(Constants.DM_SMS_CONTENT).contains(
"//USR;0")) {
// set status to disabled
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
Editor editor = settings.edit();
editor.putString("status", "0");
editor.commit();
stopSelf();
// check for Enable or Disable Value - if set to any other
// character
}
}
}
return START_NOT_STICKY;
}
private Intent Intent() {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
if (Config.DEVELOPMENT) {
period = Constants.PERIOD;
delay_interval = Constants.DELAY_INTERVAL;
} else {
Bundle extras = getIntent().getExtras();
period = Constants.DEBUG_PERIOD;
delay_interval = Constants.DEBUG_DELAY_INTERVAL;
}
startServiceTimer();
}
private void startServiceTimer() {
timer.schedule(new TimerTask() {
public void run() {
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
if (settings.getString("status", "0").equals(1)) {
// get Wifi and Mobile traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.###");
String tag = ";";
String mobileStr = nf.format(mobileBytes);
String totalStr = nf.format(totalBytes);
String info = String.format("CO%s,WO%s", tag, mobileStr,
totalStr);
// save Network and Wifi data in sharedPreferences
SharedPreferences cnwn = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
Editor editor = cnwn.edit();
editor.putString("last_month", info);
editor.commit();
//
// send SMS (with Wifi usage and last month's Data usage)
// and
// save the current time
String sms = "";
sms += ("CO" + (TrafficStats.getMobileRxBytes() + TrafficStats
.getMobileTxBytes()) / 1000000);
sms += ("WO" + (TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes() - (TrafficStats
.getMobileRxBytes() + TrafficStats
.getMobileTxBytes())) / 1000000);
SmsManager smsManager = SmsManager.getDefault();
if (Config.DEVELOPMENT) {
String shortCode = settings.getString(
Constants.PREFS_KEY_SHORT_CODE,
Constants.DEFAULT_SHORT_CODE);
smsManager.sendTextMessage(shortCode, null,
sms + cnwn.getString("last_month", ""), null,
null);
editor.putLong("smstimestamp",
System.currentTimeMillis());
editor.commit();
} else {
SmsManager ackSMS = SmsManager.getDefault();
smsManager.sendTextMessage(
Constants.DEFAULT_SHORT_CODE, null,
sms + cnwn.getString("last_month", ""), null,
null);
}
}
}
}, delay_interval, period);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
}
private void startServiceTimer() {
timer.schedule(new TimerTask() {
public void run() {
SharedPreferences settings = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
if (settings.getString("status", "0").equals(1)) {
// get Wifi and Mobile traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.###");
String tag = ";";
String mobileStr = nf.format(mobileBytes);
String totalStr = nf.format(totalBytes);
String info = String.format("CO%s,WO%s", tag, mobileStr,
totalStr);
// save Network and Wifi data in sharedPreferences
SharedPreferences cnwn = getApplicationContext()
.getSharedPreferences(Constants.PREFS_NAME, 0);
Editor editor = cnwn.edit();
editor.putString("last_month", info);
editor.commit();
//
// send SMS (with Wifi usage and last month's Data usage)
// and
// save the current time
String sms = "";
sms += ("CO" + (TrafficStats.getMobileRxBytes() + TrafficStats
.getMobileTxBytes()) / 1000000);
sms += ("WO" + (TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes() - (TrafficStats
.getMobileRxBytes() + TrafficStats
.getMobileTxBytes())) / 1000000);
StringBuilder b = new StringBuilder();
b.replace(sms.lastIndexOf("CN") - 1, sms.lastIndexOf("CN") + 2, "CO" );
b.replace(sms.lastIndexOf("WN") - 1, sms.lastIndexOf("WN") + 2, "WO" );
sms = b.toString();
SmsManager smsManager = SmsManager.getDefault();
if (Config.DEVELOPMENT) {
String shortCode = settings.getString(
Constants.PREFS_KEY_SHORT_CODE,
Constants.DEFAULT_SHORT_CODE);
smsManager.sendTextMessage(shortCode, null,
sms + cnwn.getString("last_month", ""), null,
null);
editor.putLong("smstimestamp",
System.currentTimeMillis());
editor.commit();
} else {
SmsManager ackSMS = SmsManager.getDefault();
smsManager.sendTextMessage(
Constants.DEFAULT_SHORT_CODE, null,
sms + cnwn.getString("last_month", ""), null,
null);
}
}
String str = "USI;1;3056090866;06/16/58/06/24/13;CN25.48,WN86.957;CN34.931,WN16.656";
StringBuilder b = new StringBuilder(str);
b.replace(str.lastIndexOf("CN") - 1, str.lastIndexOf("CN") + 2, "CO" );
b.replace(str.lastIndexOf("WN") - 1, str.lastIndexOf("WN") + 2, "WO" );
str = b.toString();