我已经为Tracker编写了一个应用程序;每5分钟运行一次的服务。它在Samsung Galaxy J7 Prime(Android 7.0)和Samsung Galaxy Tab A(Android 7.1)上运行良好,但是当我在Lenovo A2010(Android 5.1)上运行时,该服务无法正常工作。我不知道是导致问题的原因是我的代码还是设备。
这是服务停止时的日志:
10-08 09:01:31.122 721-737/? E/JavaBinder: *** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
这是我的服务,AppService.java
:
public class AppService extends Service {
private MyThread thread;
PowerManager.WakeLock wl;
DatabaseHelper myDb;
private static final String tracker = "Tracker";
String result=null,status=null,statusresult=null;
String stusername;
String imeiids;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!thread.isAlive()) {
thread.start();
}
return START_STICKY;
}
@Override
public void onDestroy() {
if (thread.isAlive()) {
stopService(new Intent(this, AppService.class));
}
super.onDestroy();
}
@Override
public void onCreate() {
Toast.makeText(AppService.this,"Start...",Toast.LENGTH_SHORT).show();
thread = new MyThread();
myDb = new DatabaseHelper(this);
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
stusername = shared.getString("username", "not found!").toString();
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences.Editor editor = shared.edit();
if(c.getDeviceId()==null){
editor.commit();
}
else{
editor.putString("imeiid", c.getDeviceId());
editor.commit();
}
}
}
private class MyThread extends Thread {
private static final String tag = "Sevice Demo";
private static final int delay = 60000;//60000=30sec/1minute
private int roundNumber = 0;
private boolean finishService = false;
@Override
public void run() {
while (true) {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
if(ContextCompat.checkSelfPermission(AppService.this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imeiids = c.getDeviceId();
}
if(imeiids== null){
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
imeiids=shared.getString("imeiid", "").toString();
}
Date current = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String currentDateandTime = sdf.format(current);
if(!stusername.equals("not found!")){
//////////////////////////////////// Open GPS //////////////////////////////////////
int off=0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if(off==0){
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
////////////////////////////////////////////////////////////////////////////////////
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDateString = formatter.format(currentTime);
SimpleDateFormat formatstr = new SimpleDateFormat("EEE", Locale.US);
final String formattedDayString = formatstr.format(currentTime);
if (!haveNetworkConnection()) {
/*no network connect*/
}
else{
Cursor res = myDb.getDatasync(stusername);
if(res.getCount()==0){
Log.d("dddd", "no data");
}
else{
String datetimes=null,lats=null,longs=null;
res.moveToFirst();
do{
final String ids=res.getString(0);
datetimes=res.getString(1);
lats=res.getString(3);
longs=res.getString(4);
final String finalDatetimes = datetimes;
final String finalLats = lats;
final String finalLongs = longs;
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... params) {
String location_url = "http://_____._________/__________/______________________.php";
try {
URL url = new URL(location_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("staffcode", "UTF-8") + "=" + URLEncoder.encode(stusername, "UTF-8")+ "&"
+ URLEncoder.encode("dateTime", "UTF-8") + "=" + URLEncoder.encode(finalDatetimes, "UTF-8") + "&"
+ URLEncoder.encode("lat", "UTF-8") + "=" + URLEncoder.encode(finalLats, "UTF-8") + "&"
+ URLEncoder.encode("lon", "UTF-8") + "=" + URLEncoder.encode(finalLongs, "UTF-8") + "&"
+ URLEncoder.encode("imei", "UTF-8") + "=" + URLEncoder.encode(imeiids, "UTF-8") + "&"
+ URLEncoder.encode("app", "UTF-8") + "=" + URLEncoder.encode("T:1.0", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
JSONObject jsonObject = new JSONObject(result.toString());
for (int i = 0; i < jsonObject.length(); i++)
{
status=(jsonObject.getString("status")); //Get Status
statusresult=(jsonObject.getString("statusresult"));
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(status.equals("success")&& statusresult.equals("success")){
boolean isUpdate = myDb.updateDatasync(ids);
if(isUpdate) {
Log.d("Get Data ", "Updated");
}
else {
Log.d("Get Data ", "not updated");
}
}
else{
}
}
}.execute();
}while(res.moveToNext());
}
}
Cursor res = myDb.getData(stusername);
if (res.getCount() ==0) {
Log.d("dddd", "no data");
}
else {
res.moveToFirst();
do{
String asubstring = String.valueOf(res.getString(1)).substring(11, 16);
String datesub = res.getString(1).substring(0, 10);
if(currentDateandTime.equals(datesub)){ /* Today */ }
else{
//Not Today
if(!res.getString(5).equals("1")) { }
else{ // If Sync = 1 = Sync Success
boolean isDeleteSync = myDb.deleteDataSync(res.getString(0));
if(isDeleteSync) {
Log.d("Log Delete ", "Deleted");
}
else {
Log.d("Log Delete ", "Can't Deleted");
}
}
}
}while(res.moveToNext());
}
if (formattedDayString.equals("Sun")) {
}
else {
String hour = formattedDateString.substring(11, 13);
String minute = formattedDateString.substring(14, 16);
Integer ins = Integer.parseInt(minute);
if (hour.equals("08") || hour.equals("09") || hour.equals("10") || hour.equals("11") || hour.equals("12")
|| hour.equals("13") || hour.equals("14") || hour.equals("15") || hour.equals("16") || hour.equals("17")
|| hour.equals("18")) {
if((hour.equals("18"))&&(ins<=0)){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
if((!hour.equals("18"))){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
}
else{
}
}
try {
stopService(new Intent(AppService.this,GetLocation.class));
sleep(delay);
run();
}
catch (InterruptedException e) {
e.printStackTrace();
}
wl.release();
if (finishService) {
return;
}
}
}
}
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
这是我的 DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Tracker.db";
public static final String TABLE_NAME = "LocationMessenger";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "USERNAME";
public static final String COL_4 = "LATITUDE";
public static final String COL_5 = "LONGITUDE";
public static final String COL_6 = "SYNC";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"DATE TEXT,USERNAME TEXT,LATITUDE TEXT,LONGITUDE TEXT,SYNC TEXT )");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"0");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public boolean insertDataSuccess(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"1");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public Cursor getData(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? ",new String[] { username });
return res;
}
public Cursor getDataforsync(String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,id);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where ID= ? and SYNC = ?",new String[] { id,"0" });
return res;
}
public Cursor getDatasync(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? and SYNC = ?",new String[] { username,"0" });
return res;
}
public boolean deleteData(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { String.valueOf(id) });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean deleteDataSync(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { id });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean updateDatasync(String id){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_6,"1");
long result = db.update(TABLE_NAME,contentValues,"ID=" + id,null);
if(result == -1) {
return false;
}
else{
return true;
}
}
}