Ошибок нет, все работает, только они "умирают" после перезагрузки или если долго нет сети интернет. Вот код:
AndroidManifest:
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
| <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".ForegroundService"
android:enabled="true"
android:exported="true"/>
<receiver
android:name=".MyReceiverForeground"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"/>
<service
android:name=".MyServiceGeolocation"
android:enabled="true"
android:exported="true"/>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiverGeolocation"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</application>
</manifest> |
|
ForegroundService:
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
| public class ForegroundService extends Service {
private static final String LOG_TAG = "ForegroundService";
private boolean work_geolocation = true;
private boolean work_online_user = true;
RemoteViews remoteViews;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "onStartCommand");
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ForegroundService.class);
previousIntent.setAction(Constants.ACTION.PREV_ACTION);
PendingIntent pgeolocation = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(Constants.ACTION.PLAY_ACTION);
PendingIntent ponlineuser = PendingIntent.getService(this, 0,
playIntent, 0);
remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.service_layout);
remoteViews.setImageViewResource(R.id.ivGeolocation, R.drawable.image_checkbox_true);
remoteViews.setImageViewResource(R.id.ivOnlineUser, R.drawable.image_checkbox_true);
remoteViews.setOnClickPendingIntent(R.id.ivGeolocation, pgeolocation);
remoteViews.setOnClickPendingIntent(R.id.ivOnlineUser, ponlineuser);
MyServiceGeolocation.setServiceAlarm(this, work_geolocation);
MyService.setServiceAlarm(this, work_online_user);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setCustomContentView(remoteViews)
.build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
Log.i(LOG_TAG, "Geolocation");
updateGeolocation();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
Log.i(LOG_TAG, "OnlineUser");
updateOnlineUser();
} else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
public void updateGeolocation() {
NotificationManager mgr = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
if(work_geolocation) {
work_geolocation = false;
remoteViews.setImageViewResource(R.id.ivGeolocation, R.drawable.image_checkbox_false);
MyServiceGeolocation.setServiceAlarm(this, work_geolocation);
} else {
work_geolocation = true;
remoteViews.setImageViewResource(R.id.ivGeolocation, R.drawable.image_checkbox_true);
MyServiceGeolocation.setServiceAlarm(this, work_geolocation);
}
Notification notif = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContent(remoteViews)
.build();
mgr.notify(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notif);
}
public void updateOnlineUser() {
NotificationManager mgr = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
if(work_online_user) {
work_online_user = false;
remoteViews.setImageViewResource(R.id.ivOnlineUser, R.drawable.image_checkbox_false);
MyService.setServiceAlarm(this, work_online_user);
} else {
work_online_user = true;
remoteViews.setImageViewResource(R.id.ivOnlineUser, R.drawable.image_checkbox_true);
MyService.setServiceAlarm(this, work_online_user);
}
Notification notif = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContent(remoteViews)
.build();
mgr.notify(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notif);
}
@Override
public void onDestroy()
{
super.onDestroy();
// перезапуск сервиса
Intent startIntent = new Intent(this, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// перезапуск сервиса
Intent startIntent = new Intent(this, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
} |
|
MyReceiverForeground:
Java | 1
2
3
4
5
6
7
| public class MyReceiverForeground extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
context.startService(startIntent);
}
} |
|
MyService:
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
| public class MyService extends Service {
private static final int INTERVAL_CALL = 10;
LastTimeHandler mLastTimeHandler;
ThumbnailDownloader mThumbnailDownloader;
private final IBinder mIBinder = new LocalBinder();
private Handler mHandler = null;
public static Intent newIntent(Context context) {
return new Intent(context, MyService.class);
}
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if(mThumbnailDownloader == null) {
mThumbnailDownloader = new ThumbnailDownloader(getApplicationContext());
}
if(mLastTimeHandler == null) {
mLastTimeHandler = new LastTimeHandler(getApplicationContext());
}
if(mHandler != null) {
mThumbnailDownloader.setHandler(mHandler);
}
mThumbnailDownloader.currentSales();
Date date = new Date();
SimpleDateFormat newDayFormatForDateNow = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String format = newDayFormatForDateNow.format(date);
String date1 = "08:00";
String date2 = "23:00";
String ddate1 = changeTime(format, date1);
String ddate2 = changeTime(format, date2);
try {
if(newDayFormatForDateNow.parse(ddate1).before(newDayFormatForDateNow.parse(ddate2))) {
Log.d("MyServiceTimeChanged", "onStartCommand date без нового дня!");
if(newDayFormatForDateNow.parse(newDayFormatForDateNow.format(date)).after(newDayFormatForDateNow.parse(ddate1)) &&
newDayFormatForDateNow.parse(newDayFormatForDateNow.format(date)).before(newDayFormatForDateNow.parse(ddate2))) {
mLastTimeHandler.onlineUser();
} else {
}
} else {
String ndate1 = changeTime(format, date1);
String ndate2 = changeTime(format, date2);
String new_day = changeTime(format, "00:00");
if(newDayFormatForDateNow.parse(newDayFormatForDateNow.format(date)).after(newDayFormatForDateNow.parse(new_day))) {
if(newDayFormatForDateNow.parse(newDayFormatForDateNow.format(date)).before(newDayFormatForDateNow.parse(ndate2))) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(newDayFormatForDateNow.parse(ndate1));
calendar1.add(Calendar.DATE, -1);
ndate1 = newDayFormatForDateNow.format(calendar1.getTime());
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(newDayFormatForDateNow.parse(ndate2));
calendar.add(Calendar.DATE, 1);
ndate2 = newDayFormatForDateNow.format(calendar.getTime());
if(newDayFormatForDateNow.parse(newDayFormatForDateNow.format(date)).after(newDayFormatForDateNow.parse(ndate1)) &&
newDayFormatForDateNow.parse(newDayFormatForDateNow.format(date)).before(newDayFormatForDateNow.parse(ndate2))) {
mLastTimeHandler.onlineUser();
} else {
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return START_STICKY;
}
private String changeTime(String date, String time) {
String temp = date.substring(0, 10);
temp += " ";
temp += time;
return temp;
}
public static void setServiceAlarm(Context context, boolean isOn) {
Intent i = MyService.newIntent(context);
PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(isOn) {
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), INTERVAL_CALL, pi);
} else {
alarmManager.cancel(pi);
pi.cancel();
}
}
@Override
public void onDestroy()
{
super.onDestroy();
if(mHandler != null)
{
mHandler = null;
}
// перезапуск сервиса
setServiceAlarm(this, true);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// перезапуск сервиса
setServiceAlarm(this, true);
}
public IBinder onBind(Intent intent) {
return mIBinder;
}
public class LocalBinder extends Binder
{
public MyService getInstance()
{
return MyService.this;
}
}
public void setHandler(Handler handler)
{
mHandler = handler;
}
} |
|
MyReceiver:
Java | 1
2
3
4
5
| public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
MyService.setServiceAlarm(context, true);
}
} |
|
MyServiceGeolocation:
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
| public class MyServiceGeolocation extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int INTERVAL_CALL = 10;
private LocationRequest mLocationRequest;
private GoogleApiClient googleApiClient;
private Location location;
public static Intent newIntent(Context context) {
return new Intent(context, MyServiceGeolocation.class);
}
public void onCreate() {
super.onCreate();
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(1);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1);
googleApiClient.connect();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private com.google.android.gms.location.LocationListener locationListener =
new com.google.android.gms.location.LocationListener() {
public void onLocationChanged(Location location) {
float user_latitude = (float) location.getLatitude();
float user_longitude = (float) location.getLongitude();
new BaseModel().setGeolocation(new BaseModel.LoadUserCallback() {
@Override
public void onLoad(String result) {
}
@Override
public void onError(String error) {
}
}, "296", user_latitude, user_longitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
mLocationRequest,
locationListener);
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if(location != null) {
float user_latitude = (float) location.getLatitude();
float user_longitude = (float) location.getLongitude();
new BaseModel().setGeolocation(new BaseModel.LoadUserCallback() {
@Override
public void onLoad(String result) {
}
@Override
public void onError(String error) {
}
}, "296", user_latitude, user_longitude);
} else {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
public static void setServiceAlarm(Context context, boolean isOn) {
Intent i = MyServiceGeolocation.newIntent(context);
PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(isOn) {
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), INTERVAL_CALL, pi);
} else {
alarmManager.cancel(pi);
pi.cancel();
}
}
@Override
public void onDestroy()
{
// перезапуск сервиса
googleApiClient.disconnect();
setServiceAlarm(this, true);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// перезапуск сервиса
setServiceAlarm(this, true);
}
public IBinder onBind(Intent intent) {
return null;
}
} |
|
MyReceiverGeolocation:
Java | 1
2
3
4
5
| public class MyReceiverGeolocation extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
MyServiceGeolocation.setServiceAlarm(context, true);
}
} |
|
И еще пробовал проблему решить через белый литс:
Java | 1
2
3
4
5
6
7
8
9
10
11
12
| @RequiresApi(api = Build.VERSION_CODES.M)
private void WhiteList() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean inWhiteList = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
inWhiteList = powerManager.isIgnoringBatteryOptimizations(getPackageName());
if (!inWhiteList) {
WhiteListDialogFragment whiteListDialogFragment = WhiteListDialogFragment.newInstance();
whiteListDialogFragment.show(PrivateOfficeActivity.this.getSupportFragmentManager(), "dialog");
}
}
} |
|
0
|