Android 4大コンポーネントサービス

11861 ワード

1、Seriveの起動と停止
//MainActivity.java


package sunny.example.servicestartstop;

import android.support.v7.app.ActionBarActivity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.Button;

import android.view.View.OnClickListener;

import android.view.View;

public class MainActivity extends ActionBarActivity {
 
private Button startService;
 private Button stopService;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  startService = (Button)findViewById(R.id.startService);
  stopService = (Button)findViewById(R.id.stopService);
  startService.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v){
    Intent intentS = new Intent(MainActivity.this,MyService.class);
    startService(intentS);
   }
  });
  stopService.setOnClickListener(new OnClickListener(){
   public void onClick(View v){
    Intent intent = new Intent(MainActivity.this,MyService.class);
    stopService(intent);
   }
   
  });
  
  
 }

/* public void onClick(View v){
  switch(v.getId()){
  case R.id.startService:
   Intent intentS = new Intent(this,MyService.class);
   startService(intentS);
   break;
  case R.id.stopService:
   Intent intent = new Intent(this,MyService.class);
   startService(intent);
   break;
  default:
   break;
  }
 }*/
 
} 

//MyService.java


package sunny.example.servicestartstop;

import android.app.Service;

import android.os.IBinder;

import android.content.Intent;

import android.util.Log;

import android.widget.TextView;

public class MyService extends Service{
 

@Override
 public IBinder onBind(Intent intent){
  return null;
 }
 
 @Override
 public void onCreate(){
  super.onCreate();
  
//TextView onCreate = (TextView)findViewById(R.id.onCreate); Service     
 
 Log.d("MyService","onCreate excuted");
 }
 @Override
 public int onStartCommand(Intent intent,int flags,int startId){
  Log.d("MyService","onStartCommand excuted");
  return super.onStartCommand(intent, flags, startId);
 }
 @Override
 public void onDestroy(){
  super.onDestroy();
  Log.d("MyService","onDestroy excuted");
 }
}
<!--activity_main -->


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/startService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="StartService" />
    <Button
        android:id="@+id/stopService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="StopService"/>
  <!-- <TextView
        android:id="@+id/onCreate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/onStartCommand"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        
        />
    <TextView
        android:id="@+id/onDestroy"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />  --> 
       
</LinearLayout> 


<!--AndroidManifest.xml       Activity  -->

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sunny.example.servicestartstop"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service android:name=".MyService"></service>
    </application>
</manifest>

2、ActivityとService通信
 
//MainActivity.java



package sunny.example.servicestartstop;


import android.support.v7.app.ActionBarActivity;


import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.widget.Button;

import android.view.View.OnClickListener;

import android.view.View;

public class MainActivity extends ActionBarActivity {
 private Button startService;
 private Button stopService;
 private Button bindService;
 private Button unBindService;

/*        DownloadBinder  downloadBinder, Activity     DownloadBinder   public  */
 
private MyService.DownloadBinder downloadBinder;
 private ServiceConnection connection = new ServiceConnection(){
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   // TODO Auto-generated method stub
   downloadBinder = (MyService.DownloadBinder) service;
   downloadBinder.startDownload();
   downloadBinder.getProgress();
  }
  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO Auto-generated method stub
   
  }
  
 };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  startService = (Button)findViewById(R.id.startService);
  stopService = (Button)findViewById(R.id.stopService);
  unBindService = (Button)findViewById(R.id.unBindService);
  bindService = (Button)findViewById(R.id.bindService);
  startService.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v){
    Intent intentS = new Intent(MainActivity.this,MyService.class);
    startService(intentS);
   }
  });
  stopService.setOnClickListener(new OnClickListener(){
   public void onClick(View v){
    Intent intent = new Intent(MainActivity.this,MyService.class);
    stopService(intent);
   }
   
  });
  
  bindService.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent bindIntent = new Intent(MainActivity.this,MyService.class);
    
    /*boolean android.content.ContextWrapper.bindService(Intent service, ServiceConnection conn, int flags)
     Connect to an application service, creating it if needed. 
     This defines a dependency between your application and the service.
      For example, if this Context is an Activity that is stopped, the 
      service will not be required to continue running until the Activity
       is resumed. 
      */
    bindService(bindIntent,connection,BIND_AUTO_CREATE);// MainActivity MyService  
/*BIND_AUTO_CREATE:Flag for bindService: automatically create the service as long as the binding exists.
 *   Activity Service         Service,   MyService  onCreate(),    onStartCommand() */
    
   }
   
  });
  unBindService.setOnClickListener(new OnClickListener(){
 
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    /*void android.content.ContextWrapper.unbindService(ServiceConnection conn)*/
    unbindService(connection);
   }
   
  });
  
 }
/* public void onClick(View v){
  switch(v.getId()){
  case R.id.startService:
   Intent intentS = new Intent(this,MyService.class);
   startService(intentS);
   break;
  case R.id.stopService:
   Intent intent = new Intent(this,MyService.class);
   startService(intent);
   break;
  default:
   break;
  }
 }*/
 
} 

//MyService.java

package sunny.example.servicestartstop;


import android.app.Service;

import android.os.Binder;

import android.os.IBinder;

import android.content.Intent;

import android.util.Log;

public class MyService extends Service{
 private DownloadBinder mBinder = new DownloadBinder();
 
 class DownloadBinder extends Binder{
 
 public void startDownload(){
  /*int android.util.Log.d(String tag, String msg)
   Send a DEBUG log message.
   Parameters:
    tag Used to identify the source of a log message. 
    It usually identifies the class or activity where the log call occurs.
    msg The message you would like logged.*/
  Log.d("MyService","startDownload executed");
 }
 
 public int getProgress(){
  Log.d("MainActivity","getProgress executed");
  return 0;
 }
 }
 /*android.os.IBinder
  * Do not implement this interface directly, instead extend from Binder. */
 @Override
 public IBinder onBind(Intent intent){
  return mBinder;
 }
 
 @Override
 public void onCreate(){
  super.onCreate();
  //TextView onCreate = (TextView)findViewById(R.id.onCreate); Service     
  
  Log.d("MyService","onCreate excuted");
 }
 @Override
 public int onStartCommand(Intent intent,int flags,int startId){
  Log.d("MyService","onStartCommand excuted");
  return super.onStartCommand(intent, flags, startId);
 }
 @Override
 public void onDestroy(){
  super.onDestroy();
  Log.d("MyService","onDestroy excuted");
 }
}

3、IntentService
サービスと異なり、IntentServiceはstopSelf()を呼び出す必要はなく、サービスが終了すると自動的に停止します.
//MainActivity.java 


package sunny.example.serviceintentservice;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.Button;

import android.view.View.OnClickListener;

import android.view.View;

import android.content.Intent;

public class MainActivity extends ActionBarActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  Button startIntentService = (Button)findViewById(R.id.startIntentService);
  startIntentService.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v){
    Intent intentService = new Intent(MainActivity.this,MyIntentService.class);
    startService(intentService);
   }
  });
 }
 }
 
//MyIntentService.java
 
 package sunny.example.serviceintentservice;

import android.app.IntentService;

import android.content.Intent;

import android.util.Log;

public class MyIntentService extends IntentService{
 //         
 public MyIntentService(String name) {
  super(name);
  // TODO Auto-generated constructor stub
 }
 
 /*void android.app.IntentService.onHandleIntent(Intent intent)
 This method is invoked on the worker thread with a request to process.
  Only one Intent is processed at a time, but the processing happens on
  a worker thread that runs independently from other application logic. 
  So, if this code takes a long time, it will hold up other requests to 
  the same IntentService, but it will not hold up anything else. When all 
  requests have been handled, the IntentService stops itself, so you should not call stopSelf.
 IntentService           ,    stopSelf()*/

 @Override
 protected void onHandleIntent(Intent intent) {
  // TODO Auto-generated method stub
  Log.d("MyIntentService","Thread id is"+Thread.currentThread().getId());
 }
}