当我单击前台通知服务时如何保持活动状态

时间:2019-05-02 10:50:07

标签: android android-activity android-service android-notifications

如果当我的活动不在多任务中时单击我的前台服务通知,则我的活动“重新启动”,文本/开关状态被重置。那么,如何保持这种状态呢?

我尝试过android:launchMode="singleInstance",但仅在活动处于多任务状态时才起作用:/

MyActivity.java

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        testConnection = findViewById(R.id.testButton);
        enableBot = findViewById(R.id.switch2);
        url = findViewById(R.id.editText3);
        url_send = findViewById(R.id.editText5);
        apiToken = findViewById(R.id.editText4);
        textLog = findViewById(R.id.textView);
        textLog.setText("\n#[" + formatTime() + "] - Démarrage de l'application...");

        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.SEND_SMS},
                1);

        connection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                SMSService.SMSServiceBinder binderr=(SMSService.SMSServiceBinder)service;
                services=binderr.getServiceSystem();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        createNotificationChannel();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // BOUTON CENTRALE
       /* testConnection.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendAndRequestResponse();
            }

        });*/

        enableBot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked == true) {

                    textLog.setText("\n###########################" + textLog.getText().toString());
                    //textLog.setText("\n#" + formatTime() + " - Vérification reseau/internet..." + textLog.getText().toString());

                    textLog.setText("\n#[" + formatTime() + "] - Démarrage du Bot..." + textLog.getText().toString());
                    interfaceOff();
                    testConnection.setBackgroundColor(Color.YELLOW);

                    textLog.setText("\n#[" + formatTime() + "] - Vérification connection internet..." + textLog.getText().toString());

                    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                    if (mWifi.isConnected()) {                        // Do whatever

                        textLog.setText("\n#[" + formatTime() + "] - Connecté en Wifi !" + textLog.getText().toString());
                        codeWifi = true;
                    } else {
                        textLog.setText("\n#[" + formatTime() + "] - Veuillez activé le wifi !" + textLog.getText().toString());
                        codeWifi = false;
                    }


                    string_url = url.getText().toString();
                    string_url_send = url_send.getText().toString();

                    string_apiToken = apiToken.getText().toString();

                    //Fonction de contrôle de connection
                    if (codeWifi == false) {

                        Toast.makeText(MainActivity.this, "Impossible de se connecter !", Toast.LENGTH_SHORT).show();
                        testConnection.setBackgroundColor(Color.RED);
                        interfaceOn();
                        //textLog.setText("\n#[" + formatTime() + "] - Echec connection..." + textLog.getText().toString());
                        textLog.setText("\n#[" + formatTime() + "] - Désactivation du bot..." + textLog.getText().toString());
                        textLog.setText("\n###########################" + textLog.getText().toString());
                        return;

                    }
                    textLog.setText("\n#[" + formatTime() + "] - Connection..." + textLog.getText().toString());
                    Toast.makeText(MainActivity.this, "Bot Sms activé !", Toast.LENGTH_SHORT).show();
                    testConnection.setBackgroundColor(Color.GREEN);
                    // textLog.setText("\n#[" + formatTime() + "] - Connection Réussi..." + textLog.getText().toString());
                    // Faire une requête toutes les x minutes.
                    intent = new Intent(getApplicationContext(), SMSService.class);
                    intent.putExtra("url_get", string_url);
                    intent.putExtra("url_post", string_url_send);
                    bindService(intent, connection, Context.BIND_AUTO_CREATE);
                    startService(intent);


                } else {
                    Toast.makeText(MainActivity.this, "Bot Sms désactivé !", Toast.LENGTH_SHORT).show();
                    textLog.setText("\n#[" + formatTime() + "] - Désactivation du bot..." + textLog.getText().toString());
                    textLog.setText("\n###########################" + textLog.getText().toString());
                    testConnection.setBackgroundColor(Color.RED);
                    interfaceOn();
                    unbindService(connection);
                    stopService(intent);
                    return;
                }
            }
        });


    }

前台服务

 @Override
    public void onCreate(){
        super.onCreate();
        Toast.makeText(getApplicationContext(), "CFCFCFGCG", Toast.LENGTH_SHORT).show();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // On démarre le service, et on le garde actif
        //TODO do something useful

        string_url_get = intent.getExtras().getString("url_get");
        string_url_post = intent.getExtras().getString("url_post");

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Exemple Service")
                .setContentText(string_url_get)
                .setSmallIcon(R.drawable.ic_android)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);
        handler = new Handler();
        r = new Runnable() {
            @Override
            public void run() {

                if(killme == true && nbSMSforkill <= 0){
                    handler.removeCallbacks(r);
                    stopForeground(true);
                }else {
                    //textLog.setText("\n#[" + formatTime() + "] - Envoie requête a l'API..." + textLog.getText().toString());
                    jsonRequest();
                }
            }
        };
        //Lancement du Handler
        handler.postDelayed(r, 1000);
        Toast.makeText(getApplicationContext(), "COUCOU", Toast.LENGTH_SHORT).show();
        return Service.START_REDELIVER_INTENT;
    }

    public class SMSServiceBinder extends Binder {
        public SMSService getServiceSystem(){
            return SMSService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        killme = true;
        Log.d("Response", "SERVICE ENDING");


    }
    @Override
    public IBinder onBind(Intent intent) {
        // Interface de communication
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return binder;
    }

我认为我没有保存stateInstance,但是,这对我来说是第一次在开发Android上使用,我迷路了:/

0 个答案:

没有答案
相关问题