应用程序在后台运行时无法显示通知

问题描述

我正在尝试使用AlarmManager,JobIntentService,broadcastReceiver创建一个报警应用程序,但是我的应用程序仅在其前台显示时才显示通知。我从最近的应用中清除应用后,通知将立即停止显示。我想在间隔后以及应用处于后台状态时显示通知

MainActivity

public class MainActivity extends AppCompatActivity {
    final long intervalPeriod=10000;
    AlarmManager mAlarmManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NotificationChannel notificationChannel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel("default","primary",notificationmanager.IMPORTANCE_DEFAULT);

            notificationmanager manager = (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) manager.createNotificationChannel(notificationChannel);

            mAlarmManager=(AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE);
            PendingIntent intent=PendingIntent.getbroadcast(getApplicationContext(),NotificationUpdate.REQUEST_CODE,new Intent(getApplicationContext(),NotificationUpdate.class),PendingIntent.FLAG_UPDATE_CURRENT);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.MINUTE,Calendar.getInstance().get(Calendar.MINUTE)+1);
            calendar.set(Calendar.SECOND,0);


            mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),intervalPeriod,intent);


        }
    } }

NotificationUpdate

public class NotificationUpdate extends broadcastReceiver {
    public static final String TAG="trybroad";
    public static final int REQUEST_CODE = 12345;

    @Override
    public void onReceive(Context context,Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            AlarmService.enqueueWork(context,new Intent());
        }
        Log.d(TAG,"onReceive: ");
        Intent newintent=new Intent(context,AlarmService.class);
        AlarmService.enqueueWork(context,newintent);
        //updateNotification(context);
    }
}

AlarmService

public class AlarmService extends JobIntentService {
    public static final String TAG="tryService";
    public static final int JOB_ID = 100;
    public static final int NOTIF_ID = 56;
    long timestamp;
    public static void enqueueWork(Context context,Intent work) {
        Log.d(TAG,"enqueueWork: ");
        enqueueWork(context,AlarmService.class,JOB_ID,work);
    }
    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Log.d(TAG,"onHandleWork: ");
        if(isstopped()){
            return;
        }
        updateNotification();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printstacktrace();
        }
    }
    private void updateNotification(){
        //Log.d(TAG,"updateNotification: "+ Calendar.getInstance().getTime());
        Log.d(TAG,"updateNotification: ");
        Intent intent=new Intent(this,DemoApp.class);
        PendingIntent pendingIntent=PendingIntent.getActivity(this,intent,0);
        Notification notification = new NotificationCompat.Builder(getApplicationContext(),"default")
                .setContentTitle("title")
                .setContentText("body")
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();
        notificationmanager manager=(notificationmanager)getSystemService(Context.NOTIFICATION_SERVICE);
        if(manager!=null) manager.notify(123,notification);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"onCreate: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy: ");
    }

    @Override
    public boolean onStopCurrentWork() {
        Log.d(TAG,"onStopCurrentWork: ");
        return super.onStopCurrentWork();
    }
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.angernotification">
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <application
        android:name=".DemoApp"
        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=".NotificationUpdate"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
        <service android:name=".AlarmService"
            android:enabled="true"
            android:permission="android.permission.BIND_JOB_SERVICE"/>
    </application>

</manifest>

DemoApp类

public class DemoApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        int importance = notificationmanager.IMPORTANCE_DEFAULT;

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel notificationChannel = new NotificationChannel("default",notificationmanager.IMPORTANCE_DEFAULT);
            notificationmanager mnotificationmanager = (notificationmanager) getSystemService(NOTIFICATION_SERVICE);
            if (mnotificationmanager != null) {
                mnotificationmanager.createNotificationChannel(notificationChannel);
            }
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)