我有一个应用程序使用服务首先使用网络提供程序获取用户位置,然后找到位置时,启动下载任务以获取数据并将其发送到通知中。我的问题是,当我关闭屏幕时,服务启动大约3次,然后没有任何反应。这仅在手机未连接到电脑时发生。这是我的服务源代码和我的android清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sk.digitale.wazenotificator" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver
android:name=".NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
<service android:name=".NotificationService" android:icon="@mipmap/ic_launcher" android:label="Downloading data"/>
</application>
</manifest>
以下是服务代码:
public class NotificationService extends Service {
static String updateOnWifi;
SharedPreferences sharedpreferences;
String url;
String firstEventDescription = "";
String secondEventDescription = "";
String mp3Link = "false";
static int NOTIFICATION = 10002;
static NotificationManager nManager;
MediaPlayer mediaPlayer;
boolean vibrate;
boolean updateWiFi;
boolean updateMe;
private PowerManager.WakeLock wl;
double latitude;
double longitude;
LocationManager lm;
int radius;
String email;
static PendingIntent pi;
static AlarmManager am;
boolean run;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNjfdhotDimScreen");
wl.acquire();
sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
radius = sharedpreferences.getInt("Radius", 2);
email = sharedpreferences.getString("Email", "dummy@gmail.com");
url = sharedpreferences.getString("url", "specific url");
Log.d("tag", "new url " + url);
int updateInterval = sharedpreferences.getInt("UpdateTimeout", 20);
updateWiFi = sharedpreferences.getBoolean("Wifi", true);
vibrate = sharedpreferences.getBoolean("Vibrate", true);
run = sharedpreferences.getBoolean("Running", true);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i1 = new Intent(NotificationService.this, NotificationService.class);
pi = PendingIntent.getService(NotificationService.this, 123, i1, PendingIntent.FLAG_UPDATE_CURRENT);
if (run) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, updateInterval);
new getLocationdTask().execute();
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
} else {
am.cancel(pi);
stopSelf();
}
return START_STICKY;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void showNotification() {
Bitmap icon = BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher);
Intent targetIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String provider = NetworkUtil.getConnectivityStatusString(NotificationService.this);
Notification n;
if (provider.equalsIgnoreCase("no connection")) {
n = new Notification.Builder(this)
.setContentTitle("Waze Watchdog")
.setContentText("No connection")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(icon)
.setContentIntent(contentIntent)
.setOngoing(true).build();
} else {
n = new Notification.Builder(this)
.setContentTitle("Waze Watchdog")
.setContentText(firstEventDescription)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(icon)
.setContentIntent(contentIntent)
.setOngoing(true).build();
}
nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION, n);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer = null;
}
if (nManager != null) {
nManager.cancel(NOTIFICATION);
}
}
private class getLocationdTask extends AsyncTask implements LocationListener {
protected void onPreExecute() {
Log.d("tag", "Get location onPreExecute");
lm = (LocationManager) NotificationService.this.getSystemService(Context.LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
if (run) {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
showNotification();
} else {
if (nManager != null) {
nManager.cancel(NOTIFICATION);
}
}
} else {
if (run) {
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
latitude = 48.17;
longitude = 17.13;
}
new DownloadJSON().execute();
showNotification();
} else {
if (nManager != null) {
nManager.cancel(NOTIFICATION);
}
}
}
super.onPreExecute();
}
@Override
protected Object doInBackground(Object... params) {
return null;
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("tag", "Lat: " + String.valueOf(latitude) + " Lon: " + String.valueOf(longitude));
lm.removeUpdates(this);
new DownloadJSON().execute();
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
String abc = NetworkUtil.getConnectivityStatusString(NotificationService.this);
Log.d("Tag", "provider: " + abc);
//appendLog("actual provider: " + abc);
if ((abc.equalsIgnoreCase("mobile") || updateWiFi) && run) {
updateMe = true;
showNotification();
} else {
updateMe = false;
if (nManager != null) {
nManager.cancel(NOTIFICATION);
}
}
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
if (updateMe) {
// Retrieve JSON Objects from the given URL address
JSONObject jsonobject;
if (radius == 100) {
Log.d("tag","radius == 100");
if (url.equalsIgnoreCase("custom url")) {
jsonobject = JSONfunctions.getJSONfromURL(url + "?radius=" + String.valueOf(radius) + "&account=" + String.valueOf(email));
} else {
jsonobject = JSONfunctions.getJSONfromURL(url +"&radius=" + String.valueOf(radius) + "&account=" + String.valueOf(email));
}
} else {
if (url.equalsIgnoreCase("custom url")) {
jsonobject = JSONfunctions.getJSONfromURL(url + "?lat=" + String.valueOf(latitude) + "&lon=" + String.valueOf(longitude) + "&radius=" + String.valueOf(radius) + "&account=" + String.valueOf(email));
} else {
jsonobject = JSONfunctions.getJSONfromURL(url + "&lat=" + String.valueOf(latitude) + "&lon=" + String.valueOf(longitude) + "&radius=" + String.valueOf(radius) + "&account=" + String.valueOf(email));
}
}
if (jsonobject == null) {
url = sharedpreferences.getString("url", "custom url");
} else {
try {
firstEventDescription = jsonobject.getString("text");
if (firstEventDescription.equalsIgnoreCase(secondEventDescription)) {
firstEventDescription = secondEventDescription;
} else {
secondEventDescription = firstEventDescription;
}
url = jsonobject.getString("url");
mp3Link = jsonobject.getString("mp3");
Log.d("Tag", "url from server: " + url + " Notification display: " + firstEventDescription);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void args) {
Vibrator c = (Vibrator) NotificationService.this.getSystemService(Context.VIBRATOR_SERVICE);
c.vibrate(750);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("url", url);
editor.apply();
if (run) {
showNotification();
} else if (nManager != null) {
nManager.cancel(NOTIFICATION);
}
if (!mp3Link.equalsIgnoreCase("false")) {
/*if (vibrate) {
Vibrator v = (Vibrator) NotificationService.this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(750);
}*/
mediaPlayer = MediaPlayer.create(NotificationService.this, Uri.parse(mp3Link));
if (mediaPlayer != null) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
}
mp3Link = "false";
}
if (wl != null) {
Log.v("TAG", "Releasing wakelock");
try {
wl.release();
} catch (Throwable th) {
}
} else {
Log.e("TAG", "Wakelock reference is null");
}
}
}
这是MainActivity:
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
int step = 1;
int max = 600;
int min = 20;
int stepRadius = 1;
int maxRadius = 100;
int minRadius = 2;
int updateInterval;
int radiusValue;
static boolean isRunning = true;
String email = "dummy@gmail.com";
ArrayAdapter<String> arrayAdapter;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_dropdown_item_1line);
getEmail();
sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
CheckBox activate = (CheckBox) findViewById(R.id.Activate);
isRunning = sharedpreferences.getBoolean("Running", true);
if (isRunning) {
activate.setChecked(true);
startService(new Intent(MainActivity.this, NotificationService.class));
}
activate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
//Case 1
SharedPreferences.Editor editor = sharedpreferences.edit();
isRunning = true;
editor.putBoolean("Running", true);
editor.putString("Email", email);
editor.commit();
startService(new Intent(MainActivity.this, NotificationService.class));
} else {
stopService(new Intent(MainActivity.this, NotificationService.class));
if (NotificationService.nManager != null) {
NotificationService.nManager.cancel(NotificationService.NOTIFICATION);
}
if(NotificationService.am!=null&&NotificationService.pi!=null){
NotificationService.am.cancel(NotificationService.pi);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
isRunning=false;
editor.putBoolean("Running", false);
editor.putString("url", "http://5.9.44.5/waze/appjson.php");
editor.commit();
}
//case 2
}
});
final CheckBox updateOnWiFi = (CheckBox) findViewById(R.id.UpdateOnWiFi);
boolean wifi = sharedpreferences.getBoolean("Wifi", true);
if (wifi) {
updateOnWiFi.setChecked(true);
}
updateOnWiFi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
//Case 1
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("Wifi", true);
editor.apply();
} else {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("Wifi", false);
editor.apply();
}
//case 2
}
});
CheckBox vibration = (CheckBox) findViewById(R.id.Vibrations);
boolean vibrate = sharedpreferences.getBoolean("Vibrate", true);
if (vibrate) {
vibration.setChecked(true);
}
vibration.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
//Case 1
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("Vibrate", true);
editor.apply();
} else {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("Vibrate", false);
editor.apply();
}
//case 2
}
});
final TextView textView = (TextView) findViewById(R.id.IntervalTime);
final TextView radiusText = (TextView) findViewById(R.id.radiusValue);
SeekBar radius = (SeekBar) findViewById(R.id.radius);
radius.setMax((maxRadius - minRadius) / stepRadius);
radiusValue = sharedpreferences.getInt("Radius", 2);
if (radiusValue == 100) {
radiusText.setText("Everything");
} else {
radiusText.setText(String.valueOf(radiusValue) + "km");
}
radius.setProgress(radiusValue);
radius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
radiusValue = minRadius + (progress * stepRadius);
if (radiusValue == 100) {
radiusText.setText("Everything");
} else {
radiusText.setText(String.valueOf(radiusValue) + "km");
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("Radius", radiusValue);
editor.apply();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
SeekBar interval = (SeekBar) findViewById(R.id.interval);
interval.setMax((max - min) / step);
updateInterval = sharedpreferences.getInt("UpdateTimeout", 20);
textView.setText(String.valueOf(updateInterval) + "s");
interval.setProgress(updateInterval);
interval.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updateInterval = min + (progress * step);
textView.setText(String.valueOf(updateInterval) + "s");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("UpdateTimeout", updateInterval);
editor.apply();
}
});
}
public void getEmail() {
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
for (Account account : list) {
if (account.type.equalsIgnoreCase("com.google")) {
if (arrayAdapter != null) {
email = account.name;
Log.d("Tag", account.name);
break;
}
}
}
}
}