LoginSignup
0
0

More than 3 years have passed since last update.

android~service

Last updated at Posted at 2019-10-14

ServiceはActivity(UI)ですべての計算や情報処理を行わないで、Service Classや別のサーバーで処理すること。なお、Serviceは背景で運行していて、自体にUIがありません。

≪IntentService≫

① Service Classを作る

java classのフォルダー→ new→ service→ service(Intent)、どんなサービスでもコンストラクターは必ず作ります。今回はServiceを作ってみたかっただけなので、内容は適当にLog iを提示しただけです。

MyIntentService.java

public class MyIntentService extends IntentService {

    private static final String TAG = "MyIntentService";


    public MyIntentService() {
        //build constructor is a must
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //This is what service does.

        Log.i(TAG, "onHandleIntent: MyIntentService is running");


    }
}

② <Service>タグを追加

AndroidManifest.xml

 <service android:name=".MyIntentService"/>

③ MainActivityでServiceを執行する

MainActivity.java
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent=new Intent(this, MyIntentService.class);
        startService(intent);}

となると、Appを執行すれば、下記のLog情報が見られます。

image.png

≪Service≫

①Service Classを作る

Java Classのフォルダー→New→Service→Service
Bound serviceはここで作るつもりはなかったので、とりあえずonBind methodはnullをreturnします。次はonStartCommandとonDestroyをOverrideします。ServiceはThreadを内蔵されてないので、自分でonStartCommandの中で作ります。RunnableとThreadの内容は適当にログ情報を操作します。最後に Service.START_STICKY;をreturnします。

MyService.java
public class MyService extends Service {
    public MyService() {
    }

    private static final String TAG = "MyService";

    @Override
    public IBinder onBind(Intent intent) {
        //we do no bound service here
       return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //what you want this service to do
        Log.i(TAG, "The service is running");

        //Creating thread is needed for Service(no need for IntentService)
        Runnable r=new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<5;i++){
                    long futureTime=System.currentTimeMillis()+5000;
                    while(System.currentTimeMillis()<futureTime){
                        synchronized (this){
                        try{
                            wait(futureTime-System.currentTimeMillis());
                            Log.i(TAG, "run: The service is processing");
                        } catch (Exception e){}}
                    }
                }
            }

        };

        Thread mThread=new Thread(r);
        mThread.start();

        // when service is stopped accidentally,restart the service again
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        //what action when the service is stopped.
        Log.i(TAG, "The service is stopped");
   }

②Service ClassをMainActivityで執行します

MainActivity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent=new Intent(this, MyService.class);
        startService(intent);
    }

appをRunしたらbackgroundのLogは下記のようになります。
image.png

以上は覚書です。Bound Serviceのやり方がわかったらまたここで追加記録します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0