▼Androidメモ▼
サービス
サービスを利用するプログラムを作成する。
![]()
ソースコード
ServiceEx.java package net.npaka.serviceex; import java.util.Date; import java.util.List; import android.app.Activity; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Color; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; //サービス public class ServiceEx extends Activity implements View.OnClickListener { private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT; private Intent serviceIntent; private IMyService binder; private Button btnStart; private Button btnStop; private Button btnControl; //アクティビティ起動時に呼ばれる @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); //レイアウトの生成 LinearLayout layout=new LinearLayout(this); layout.setBackgroundColor(Color.rgb(255,255,255)); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); //ボタンの生成 btnStart=makeButton("サービスの開始","start"); layout.addView(btnStart); btnStop=makeButton("サービスの停止","stop"); layout.addView(btnStop); btnControl=makeButton("サービスの操作","control"); layout.addView(btnControl); setServiceUI(true); //サービスインテントの生成 serviceIntent=new Intent(); serviceIntent.setClassName("net.npaka.serviceex", "net.npaka.serviceex.MyService"); //サービスの接続 if (isServiceRunning("net.npaka.serviceex.MyService")) { bindService(serviceIntent,connection,BIND_AUTO_CREATE); setServiceUI(false); } } //サービスが起動中かどうか private boolean isServiceRunning(String className) { ActivityManager am=(ActivityManager)getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> serviceInfos= am.getRunningServices(Integer.MAX_VALUE); for (int i=0;i<serviceInfos.size();i++) { if (serviceInfos.get(i).service.getClassName().equals(className)) { return true; } } return false; } //サービス操作の指定 private void setServiceUI(boolean startable) { btnStart.setEnabled(startable); btnStop.setEnabled(!startable); btnControl.setEnabled(!startable); } //ボタンの生成 private Button makeButton(String text,String tag) { Button button=new Button(this); button.setTag(tag); button.setText(text); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return button; } //ボタンクリックイベントの処理 public void onClick(View v) { String tag=(String)v.getTag(); //サービスの開始 if (tag.equals("start")) { setServiceUI(false); //サービスの開始 startService(serviceIntent); //サービスの接続 bindService(serviceIntent,connection,BIND_AUTO_CREATE); } //サービスの停止 else if (tag.equals("stop")) { setServiceUI(true); //サービスの切断 unbindService(connection); //サービスの停止 stopService(serviceIntent); } //サービスの操作 else if (tag.equals("control")) { try { binder.setMessage(""+(new Date())); } catch (Exception e) { } } } //サービスコネクション private ServiceConnection connection=new ServiceConnection() { //サービス接続時に呼ばれる public void onServiceConnected(ComponentName name,IBinder service) { binder=IMyService.Stub.asInterface(service); } //サービス切断時に呼ばれる public void onServiceDisconnected(ComponentName name) { binder=null; } }; }
MyService.java package net.npaka.serviceex; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.widget.Toast; //自作サービス public class MyService extends Service { private Handler handler=new Handler(); private boolean running=false; private String message="Message"; //サービス生成時に呼ばれる @Override public void onCreate() { super.onCreate(); } //サービス開始時に呼ばれる @Override public void onStart(Intent intent,int startID) { super.onStart(intent,startID); //ノティフィケーションの表示 showNotification(this,R.drawable.icon, "自作サービスを開始しました", "自作サービス", "自作サービスを操作します"); //サービスの開始 Thread thread=new Thread(){ public void run() { running=true; while (running) { handler.post(new Runnable(){ public void run() { toast(MyService.this,message); } }); try { Thread.sleep(3000); } catch (Exception e) { } } } }; thread.start(); } //サービス停止時に呼ばれる @Override public void onDestroy() { running=false; super.onDestroy(); } //サービス接続時に呼ばれる @Override public IBinder onBind(Intent intent) { return IMyServiceBinder; } //ノティフィケーションの表示 private static void showNotification(Context context, int iconID,String ticker,String title,String message) { //ノティフィケーションオブジェクトの生成 Notification notification=new Notification(iconID, ticker,System.currentTimeMillis()); PendingIntent intent=PendingIntent.getActivity(context,0, new Intent(context,ServiceEx.class),0); notification.setLatestEventInfo(context,title,message,intent); //ノティフィケーションマネージャyの取得 NotificationManager nm=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); //ノティフィケーションのキャンセル nm.cancel(0); //ノティフィケーションの表示 nm.notify(0,notification); } //トーストの表示 private static void toast(Context context,String text) { Toast.makeText(context,text,Toast.LENGTH_SHORT).show(); } //サービスバインダ private final IMyService.Stub IMyServiceBinder=new IMyService.Stub() { public void setMessage(String msg) throws RemoteException { message=msg; } }; }
IMyService.aidl package net.npaka.serviceex; interface IMyService { void setMessage(String msg); }
AndroidManifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.npaka.serviceex" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ServiceEx" 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> <uses-sdk android:minSdkVersion="7" /> </manifest>
−戻る−