在api 19中关闭应用程序时NotificationService不起作用

时间:2019-05-20 09:09:21

标签: android android-manifest android-notifications

我有一个通知服务,但是当我关闭应用程序时,它不显示通知。

我的清单中有这个

<service
            android:name=".NotificationService"
            android:label="@string/app_name"
            android:permission="false">
            <intent-filter>
                <action android:name=".NotificationService" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

这在我的mainActivity中:

startService(new Intent(MainActivity.this, NotificationService.class));

这在我的NotificationService类中

public class NotificationService extends Service {

   Timer timer;
    TimerTask timerTask;
    String TAG = "Timers";
    int Your_X_SECS = 5;

    int a = 1;

    public NotificationService() {
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);

        startTimer();

        return START_STICKY;
    }


    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        stoptimertask();
        super.onDestroy();


    }

    //we are going to use a handler to be able to run in our TimerTask
    final Handler handler = new Handler();


    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
            initializeTimerTask();

        SharedPreferences pref = getApplicationContext().getSharedPreferences("pref01", MODE_PRIVATE);
        Your_X_SECS = Integer.valueOf(Objects.requireNonNull(pref.getString("intervalo", "3600")));

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, Your_X_SECS * 1000, Your_X_SECS * 1000); //
        //timer.schedule(timerTask, 5000,1000); //
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {


                            Intent intent = new Intent(getBaseContext(), MainActivity.class);
                            showNotification(getApplicationContext(), "Notice!", "Notice text!", intent);


                    }
                });
            }
        };
    }

我总结了服务类,但是当我打开应用程序时它正在工作。当我关闭应用程序时如何使其工作?我错过了什么吗?

0 个答案:

没有答案