android-service的簡單用法

來源:互聯網
上載者:User

標籤:

service是android開發中的四大組件之一,下面來介紹service的簡單用法

1.需要建立一個service類,該類繼承與service介面,需要實現onBind方法,這個方法之後介紹

2.建立intent對象,設定intent的目標為建立的service的類,啟動service的方法有兩種用startservice方法和bindservice方法

  兩種方法的不同在於startservice在啟動服務之後,關閉當前的activity之後service還在系統後台運行

  bindservice啟動服務後將服務與主介面綁定,主介面關閉之後service也就結束了

3.主介面與service的資訊互動需要用到aidl,需要在項目src下建立aidl包,並建立介面,會自動在gen目錄下產生對應的java檔案,這些東西都是不用進行修改的.

另外,一定記得在androiManifest中註冊service

package com.wentjiang.shixi_service;import com.wentjiang.shixi_service.aidl.MyInterface;import android.R.string;import android.app.Activity;import android.app.Service;import android.content.BroadcastReceiver;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener{    private Button mStartService,mStopService,mBindService,mUnbindService,mAidl;    private TextView mTextView;    private ServiceConnection mConn;    private MyReceiver myreceiver;    private MyInterface mInterface;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initData();        initView();    }    private void initView() {        mStartService=(Button) findViewById(R.id.startService);        mStopService=(Button) findViewById(R.id.stopService);        mBindService=(Button) findViewById(R.id.bindService);        mUnbindService=(Button) findViewById(R.id.unbindService);        mAidl=(Button) findViewById(R.id.aidl);        mTextView=(TextView) findViewById(R.id.text);        mStartService.setOnClickListener(this);        mStopService.setOnClickListener(this);        mBindService.setOnClickListener(this);        mUnbindService.setOnClickListener(this);        mAidl.setOnClickListener(this);                    }    private void initData() {        mConn=new ServiceConnection() {                        @Override            public void onServiceDisconnected(ComponentName name) {                //串連失敗時調用的方法                            }                        @Override            public void onServiceConnected(ComponentName name, IBinder service) {                //串連成功是調用的方法                Log.i("串連成功了", "---");                mInterface=MyInterface.Stub.asInterface(service);            }        };        myreceiver=new MyReceiver();        IntentFilter filter = new IntentFilter();        filter.addAction("action.went");                registerReceiver(myreceiver, filter);            }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    @Override    public void onClick(View v) {        Intent intent =new Intent(this, MyService.class);        switch (v.getId()) {        case R.id.startService:            startService(intent);            break;        case R.id.stopService:            stopService(intent);            break;        case R.id.bindService:            bindService(intent, mConn, Service.BIND_AUTO_CREATE);            break;        case R.id.unbindService:            unbindService(mConn);            break;        case R.id.aidl:            try {                int num= mInterface.getmul(10, 6);                mTextView.setText(String.valueOf(num));            } catch (RemoteException e) {                e.printStackTrace();            }        default:            break;        }    }        public class MyReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            if("action.went".equals(action)){                int num=intent.getIntExtra("num", 0);                mTextView.setText(String.valueOf(num));            }        }            }}
MainActivity
package com.wentjiang.shixi_service;import java.util.Timer;import java.util.TimerTask;import com.wentjiang.shixi_service.MainActivity.MyReceiver;import com.wentjiang.shixi_service.aidl.MyInterface;import android.R.integer;import android.app.Service;import android.content.Intent;import android.content.IntentFilter;import android.net.ConnectivityManager;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;public class MyService extends Service {    private MyReceiver mReceiver;    private MyInterface.Stub mBinder = new MyInterface.Stub() {                @Override        public int getmul(int num1, int num2) throws RemoteException {            int temp=num1*num2;            return temp;        }    };        @Override    public IBinder onBind(Intent intent) {        Log.i("onbind被調用了", "----");        return mBinder;    }    @Override    public void onCreate() {        super.onCreate();        Log.i("oncreate被調用了", "----");    }    @Override    public void onDestroy() {        Log.i("onDestroy被調用了", "---");        super.onDestroy();    }    @Override    public void onRebind(Intent intent) {        Log.i("onRebind", "---");        super.onRebind(intent);    }}
MyService

 

package com.wang.service.aidl;interface MyInterface{        int mul(int a, int b);    }
MyInterface
<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:background="#ffffff"    android:orientation="vertical"    android:padding="20dp" >    <TextView        android:id="@+id/tv"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Test"        android:textColor="#000000"        android:textSize="24sp" />    <Button        android:id="@+id/btn01"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Start Service" />    <Button        android:id="@+id/btn02"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Stop Service" />        <Button        android:id="@+id/btn03"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="bind Service" />    <Button        android:id="@+id/btn04"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="unbind Service" />        <Button        android:id="@+id/btn05"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:text="work" />   </LinearLayout>
activity_main

 

android-service的簡單用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.