自动设置通知

时间:2017-04-28 19:00:25

标签: java android java-threads

我创建了一个使用BackgroundThread扩展Thread类每2小时发送一次通知的应用程序,它运行得很好,但我关闭了应用程序,我没有收到任何通知,你可以帮我吧。

这是我的代码。

  

类BackgroundThread扩展了Thread

public class BackgroundThread extends Thread {

    boolean running = true;
    final static String ACTION = "NotifyServiceAction";
    NotificationManager notificationManager;
    Notification myNotification;
    Context context;
    static int idnotification=100;

    public BackgroundThread(Context context)
    {
        this.context=context;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }


    public synchronized void start() {
        super.start();
        notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);}


    public void run() {
        while(running){//
            try{
                sleep(10000);//l'envoi de lapplication chaque 2 h
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

             myNotification = new Notification(R.drawable.aramtres100,"Notification",System.currentTimeMillis());
            context = context.getApplicationContext();
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(myNotification)));
            //Intent i = new Intent(this.context,NotifRecep.class);
            PendingIntent pendingIntent= PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder builder= (NotificationCompat.Builder) new NotificationCompat.Builder(context).setContentIntent(pendingIntent)
                    .setSmallIcon(android.R.drawable.arrow_up_float)
                    .setContentTitle("Alarme Medicament")
                    .setContentText("Il est temps de prendre ton medicament")
                    .setAutoCancel(true)
                    .setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.newmessage));
            notificationManager.notify(idnotification,builder.build());
            idnotification++;
        }

    }
}

这是MainActivity:

public class MainActivity extends Activity {
    BackgroundThread backgroundThread;


    protected void onStart() {
        super.onStart();
        backgroundThread = new BackgroundThread(this);
        backgroundThread.setRunning(true);
        backgroundThread.start();
    }


    protected void onStop() {
        super.onStop();
        boolean retry = true;
        backgroundThread.setRunning(false);

        while (retry) {
            try {
                backgroundThread.join();
                retry = false;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

0 个答案:

没有答案