Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package at.htl_leonding.servicedemo;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.support.design.widget.FloatingActionButton;
- import android.support.design.widget.Snackbar;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.Toolbar;
- import android.util.Log;
- import android.view.View;
- import android.view.Menu;
- import android.view.MenuItem;
- public class MainActivity extends AppCompatActivity {
- private static final String LOG_TAG = MainActivity.class.getSimpleName();
- private MyService.MyServiceBinder serviceBinder;
- private ServiceConnection serviceConnection = new ServiceConnection() {
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- Log.d(LOG_TAG, "onServiceConnected()");
- serviceBinder = (MyService.MyServiceBinder) service;
- }
- @Override
- public void onServiceDisconnected(ComponentName name) {
- Log.d(LOG_TAG, "onServiceConnected()");
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
- fab.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- serviceBinder.startService();
- }
- });
- }
- @Override
- protected void onResume() {
- super.onResume();
- Intent serviceIntent = new Intent(getBaseContext(), MyService.class);
- getApplicationContext().bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
- }
- @Override
- protected void onPause() {
- getApplicationContext().unbindService(serviceConnection);
- super.onPause();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement