Одним из требований в приложении, которое я разрабатываю, является «показывать что-то на экране по событию».По сути, я сделал фоновый сервис, и в тот момент я ловлю экран на намерение и передаю его BroadcastReceiver
.Затем в приемнике я открываю действие и «показываю что-то».Однако на Android 7-8.Я думаю, что фоновую службу убивают за ночь, потому что на следующий день моя служба ничего не перехватывает, а мой получатель не получает.Я даже запрашиваю разрешение
<uses-permission
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
и переопределяю его, но служба все равно убивается.Ниже вы можете найти мой Service
класс, Receiver
класс и манифест.
Класс обслуживания
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class Services extends Service {
private static final String TAG = "Services";
private BroadcastReceiver sReceiver;
public static final String ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT";
public IBinder onBind(Intent arg) {
return null;
}
public int onStartCommand(Intent intent, int flag, int startIs) {
Log.i(TAG, "onStartCommand: " + this.toString() + " sReceiver = " + sReceiver);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(ALARM_ALERT_ACTION);
sReceiver = new Receivers(new Handler());
registerReceiver(sReceiver, filter);
if(intent != null){
LUtil.appendToLogs("Service onStartCommand " + intent.getAction() + " intent catched.");
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(sReceiver);
}
}
Класс получателя:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Handler;
import android.util.Log;
import com.mytoz.app.object.CommercialData;
import java.io.File;
import java.util.ArrayList;
public class Receivers extends BroadcastReceiver {
private static final String TAG = "Receivers";
private final Handler handler;
public Receivers(Handler handler) {
this.handler = handler;
}
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive: id = " + this.toString());
Log.i(TAG, "intent.getAction() " + intent.getAction());
LUtil.appendToLogs("onReceive " + intent.getAction() + " intent passed to receiver.");
if(LUtil.isPowerOff){
LUtil.isPowerOff = false;
return;
}
if (intent.getAction() != null) {
if(intent.getAction().equals(Services.ALARM_ALERT_ACTION)){
LUtil.lastAlarmAlert = System.currentTimeMillis();
Log.i(TAG, "onReceive: LUtil.lastAlarmAlert = " + LUtil.lastAlarmAlert);
return;
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
final int mode = am.getMode();
if (AudioManager.MODE_IN_CALL == mode) {
Log.i(TAG, "onReceive: in call");
// device is in a telephony call
} else if (AudioManager.MODE_IN_COMMUNICATION == mode) {
Log.i(TAG, "onReceive: commuunication");
// device is in communiation mode, i.e. in a VoIP or video call
} else if (AudioManager.MODE_RINGTONE == mode) {
Log.i(TAG, "onReceive: ringtone");
// device is in ringing mode, some incoming is being signalled
} else {
// SHOW SOMETHING
}
} else {
}
}
}
}
Мой манифест:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<application xmlns:tools="http://schemas.android.com/tools"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="@mipmap/app_logo"
android:label="@string/app_name"
android:largeHeap="true"
android:roundIcon="@mipmap/app_logo"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:replace="android:hardwareAccelerated"
android:name=".Mytoz">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="false" />
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
<service android:name=".Services" />
<service
android:exported="false"
android:name=".FirebaseJobService">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>
</service>
<service
android:name=".PushHandleService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<receiver
android:enabled="true"
android:exported="true"
android:name=".BootCompletedReceiver"
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" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<receiver
android:enabled="true"
android:exported="true"
android:name=".UpdateReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<activity
android:name=".SplashScreen"
android:theme="@style/SplashTheme" android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".networking.CrashReportHandle" />
<activity android:name=".LoginActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".MainActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".CommercialVideo" android:taskAffinity=".CommercialVideo" android:excludeFromRecents="true" android:configChanges="orientation"
android:screenOrientation="portrait" android:launchMode="singleTop"/>
<activity android:name=".ShopActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".InterestActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".SignUpActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible|adjustResize" />
<activity android:name=".MyAdsActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".SignUpThirdActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".SignUpSecondActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".RegisterActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".SettingsFirstActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".SettingsSecondActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".SettingsThirdActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".ItemDetailActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".CheckoutActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".DeliveryActivity" android:configChanges="orientation"
android:screenOrientation="portrait" android:windowSoftInputMode="stateVisible|adjustResize" />
<activity
android:configChanges="orientation"
android:screenOrientation="portrait"
android:name="com.braintreepayments.api.BraintreeBrowserSwitchActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="${applicationId}.braintree" />
</intent-filter>
</activity>
<activity android:name=".PaymentActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".CreditCardActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".OfferActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".ConfirmationActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".AdsSecondActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".CustomAdsVideoActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".OrderActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".OrderDetailsActivity" android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".SmartyAdsActivity"
android:configChanges="orientation|keyboardHidden|screenSize" />
</application>
</manifest>