그렇게 어렵진 않았다. 

전에 했던 거 그대로 따라함.

 

6장 - 서비스

백그라운드 : 화면 뒤의 공간서비스 : 백그라운드에서 실행되는 앱의 구성 요소 (앱의 구성요소이기 때문에 시스템에서 관리됨.)서비스는 비정상적으로 종료되더라도 시스템이 자동으로 재실행

sand-to-desert.tistory.com

 

 

1. activity_main.xml 

 

2. MainActivity.java

package com.example.doitmission_11;

public class MainActivity extends AppCompatActivity {

    EditText inputText;
    TextView outputText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        inputText = findViewById(R.id.editTextText);
        outputText = findViewById(R.id.textView2);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MyService.class);
                intent.putExtra("key",inputText.getText().toString());
                startService(intent);
            }
        });
        Intent passedIntent = getIntent();
        processIntent(passedIntent);
    }

    @Override
    protected void onNewIntent(@NonNull Intent intent) {
        processIntent(intent);
        super.onNewIntent(intent);
    }

    private void processIntent(Intent intent){
        if(intent!=null){
            String text = intent.getStringExtra("key");
            outputText.setText(text);
        }
    }
}

 

3. MyService.java

package com.example.doitmission_11;

public class MyService extends Service {
    public MyService() {
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent==null)
            return Service.START_STICKY;
        else
            processCommand(intent);
        return super.onStartCommand(intent, flags, startId);
    }

    private void processCommand(Intent intent){
        String text = intent.getStringExtra("key");
        Intent showIntent = new Intent(getApplicationContext(), MainActivity.class);

        showIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
                Intent.FLAG_ACTIVITY_SINGLE_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TOP);

        showIntent.putExtra("key",text);
        startActivity(showIntent);
    }
}

 

Service.START_STICKY

FLAG

4. 실행 결과