我的广播接收器在 Pause() 函数上工作正常,但是当我终止我的应用程序时,我的广播接收器仅在 oreo 中停止监听,但在低于 oreo 的其他 API 级别上工作正常。我还在我的 list 文件中注册了我的广播接收器,并在我的resume() 中注册了它。
我的主要 Activity 代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, BroadcastService.class));
Log.i(TAG, "Started service");
}
@Override
public void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.i(TAG, "Registered broacast receiver");
}
这是我的服务类:
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.codecollapse";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
//sendBroadcast(bi);
sendBroadcast(new Intent(getBaseContext(), CountDownReceiver.class).setAction("com.codecollapse").putExtra("countdown",millisUntilFinished));
}
@Override
public void onFinish() {
bi.putExtra("IsFinish",true);
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
@Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
这是我的接收器类
public class CountDownReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "You Poke the service", Toast.LENGTH_SHORT).show();
}
}
这是我的 list 文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidservices">
<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>
<receiver
android:name=".CountDownReceiver">
<intent-filter>
<action android:name="com.codecollapse"/>
</intent-filter>
</receiver>
<service android:name=".BroadcastService" />
</application>
最佳答案
关于java - 当应用程序被杀死时,广播接收器不会在奥利奥上监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57284013/