サービスが第二の重要性だけの活動では、アンドロイド4つの主要成分の一つである、Androidのドキュメントは、次のように彼を説明します。
サービスコンポーネントは、ユーザーまたは使用する他のアプリケーションの機能に影響を与えることなく、時間のかかる操作を表します。
アンドロイドでは、すべてのコンポーネントが、それは別のスレッドを開くのに時間のかかる操作を必要とするときサービスを使用し、メインスレッドで実行されています。しかし、サービス、より扱いやすい時間のかかる操作の使用はサービスが異なるライフサイクルを持っているので。たとえば、音楽を再生するアプリケーションは、通常、サービスによって制御されます。
サービス開始
サービスは、2つの方法で開始することができます。Context.startService()またはContext.bindService();
Context.startService()メソッドと同様の活性を起動します。
Intent i = new Intent(ServiceActivity.this, ServiceA.class);
startService(i);
サービスを開始するには、このメソッドを使用した後、サービスコールはのonCreate()とonStartCommand()メソッドでした。
サービスが停止方法されています。
Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
stopService(i);
またstopSelfサービスの()メソッドの停止を呼び出すことができます。
サービスは、操作がリソースを解放するために彼のonDestory()メソッドの破壊と呼ばれるとき。
複数の打ち上げサービス、のonCreate()メソッドがコールのみが最初に起動したとき(またはサービスの再起動の破壊)、複数回呼び出されることはありませんが、onStartCommand()メソッドが複数回呼び出されることに注意してください。
第二の方法:Context.bindService()
Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
bindService(i,connection,BIND_AUTO_CREATE);
バインド解除方法:
Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
unbindService(connection);
次のようにサービスが時にライフサイクル・アプローチ、この方法で開始しました:
bindService-> onCreate-> onBind-> unbindService-> onUnbind-> onDestroy
あなたはこのサービスの破壊の活動を破壊することができunbindServiceメソッドを呼び出すことはありませんが、メモリリークが発生した場合は、次のように、エラーが報告されます。
08-30 00:12:06.060 1937-1937/example.ylh.com E/ActivityThread: Activity example.ylh.com.service_demo.ServiceTestActivity has leaked ServiceConnection example.ylh.com.service_demo.ServiceTestActivity$1@513a0eb that was originally bound here
······
そのため、メモリリーク、または正直なバインド解除、それを防止するためです。
bindServiceの起動は、それが何であるこれは、第二はServiceConnectionで、最初の目的である、2つのパラメータを渡す必要がありますか?
必要性のServiceConnectionに、この時間を私たちは知っていたサービスを開始した後、サービス額を実行するために始めたが、どのようにして活動が相互作用することで、ServiceConnectionはインターフェイスです。
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(TAG,"onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "onServiceDisconnected");
}
};
onServiceConnected方法がすぐに[OnBind]のサービスの後と呼ばれ、仲間、結合活性およびサービスの成功を表明しました。
サービスと失敗に関連した活動を表現する方法をonServiceDisconnected、一般的に呼ばれない、バインドされていません。
onServiceConnected方法は、我々は以下、活動及びサービス会合のための値とonServiceConnected方法を返す[OnBind]のことができるように、この方法は、返り値[OnBind]のサービスであり、2番目のパラメータがIBinder、IBinderであり、2つのパラメータを取る典型的なケースであります:
XMLのアクティビティ:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:text="start"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:text="stop"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn3"
android:text="action"/>
</LinearLayout>
</RelativeLayout>
アクティビティコード:
package example.ylh.com.service_demo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import example.ylh.com.R;
/**
* Created by yanglihai on 2017/8/17.
*/
public class ServiceTestActivity extends Activity {
public static final String TAG = ServiceTestActivity.class.getSimpleName();
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ((ServiceA.MyBinder) service).getService();
Log.e(TAG,"onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "onServiceDisconnected");
}
};
private ServiceA mService ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_test_activity);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
bindService(i,connection,BIND_AUTO_CREATE);
}
});
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
unbindService(connection);
}
});
findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mService.doSomething();
}
});
}
}
サービスコード:
package example.ylh.com.service_demo;
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by yanglihai on 2017/8/17.
*/
public class ServiceA extends Service {
static final String TAG = ServiceA.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "oncreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
}
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
Log.e(TAG, "bindService");
return super.bindService(service, conn, flags);
}
@Override
public void unbindService(ServiceConnection conn) {
super.unbindService(conn);
Log.e(TAG, "unBindService");
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "onUnbind");
return super.onUnbind(intent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind" );
return mbinder;
}
public void doSomething(){
Log.e(TAG, "doSomething");
}
private MyBinder mbinder = new MyBinder();
public class MyBinder extends Binder{
public ServiceA getService(){
return ServiceA.this;
}
}
}
onServiceConnected方法では、強力なターンでのgetService()、それを操作することができますあなたが望むを介して取得するサービスのインスタンスでは、バインダーを取得します。
レセプションサービス
サービスが開始され、我々はメソッドを呼び出して停止しない場合は、サービスがバックグラウンドで実行されますが、不十分なシステムメモリは、当社のサービスを殺すことと、避けるために、システムによって殺されて、サービスがフォアグラウンドを設定することができますService.startForeground()を呼び出すことによって行われたサービス、。
コードの最初に:
package example.ylh.com.service_demo;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import example.ylh.com.R;
/**
* Created by yanglihai on 2017/8/17.
*/
public class ServiceA extends Service {
static final String TAG = ServiceA.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "oncreate");
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.btn_home_vedio);
builder.setContentTitle("视频通知");
builder.setContentText("someone send you a video");
Notification notification = builder.build();
startForeground(2,notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
}
}
onCreateでは、バックグラウンド操作の実行があるユーザーに知らせる通知を作成します。最初のパラメータstartForeground()は、これが0ではないか、またはフロントデスクを作成できないことに留意されたいint型のID、IDが必要です。
サービスが停止またはコールStopForeground(真)まで、この動作中のサービスでは、通知が消えることができるようになり、通知バー通知があるでしょう。
そのサービスの必要性は、マニフェストファイルで宣言される起動モードの種類に関係なく、を追加します。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.ylh.com" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".service_demo.ServiceA" />
</application>
</manifest>