Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.test;
- import android.support.v7.app.ActionBarActivity;
- 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.util.Log;
- import android.view.Menu;
- import android.view.MenuItem;
- public class MainActivity extends ActionBarActivity
- implements
- ServiceConnection
- {
- private final static String TAG = "MainActivity";
- private boolean mIsServiceBound;
- @Override
- protected void onCreate (Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- @Override
- protected void onStart ()
- {
- super.onStart();
- Log.v(TAG, "onStart()");
- doBindService();
- }
- @Override
- protected void onStop ()
- {
- super.onStop();
- Log.v(TAG, "onStop()");
- doUnbindService();
- }
- @Override
- public boolean onCreateOptionsMenu (Menu menu)
- {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.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();
- if (id == R.id.action_settings)
- {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- private void doBindService ()
- {
- // no need to bind if already bound
- if (!mIsServiceBound)
- {
- Log.v(TAG, "doBindService()");
- Intent intent = new Intent(this, MediaService.class);
- //intent.setComponent(mServiceName);
- // start Service
- startService(intent);
- // connect to service
- if (14 > android.os.Build.VERSION.SDK_INT)
- {
- mIsServiceBound = bindService(intent, MainActivity.this,
- Context.BIND_AUTO_CREATE);
- }
- else
- {
- // Context.BIND_IMPORTANT = 0x40
- mIsServiceBound = bindService(intent, MainActivity.this,
- Context.BIND_AUTO_CREATE | 0x40);
- }
- }
- }
- private void doUnbindService ()
- {
- if (mIsServiceBound)
- {
- Log.v(TAG, "doUnbindService()");
- // unbind the service!
- try
- {
- unbindService(MainActivity.this);
- }
- catch (IllegalArgumentException e)
- {
- Log.e(TAG, "doUnbindService()", e);
- }
- mIsServiceBound = false;
- }
- }
- @Override
- public void onServiceConnected (ComponentName name, IBinder service)
- {
- Log.v(TAG, "onServiceConnected()");
- }
- @Override
- public void onServiceDisconnected (ComponentName name)
- {
- Log.w(TAG, "onServiceDisconnected()");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement