Android 服務和廣播的使用

Android 服務和廣播的使用

服務的使用

建立服務類

 建立一個java文件,取名 mService.java,繼承Service。java

public class mService extends Service {}

返回服務控制器git

  /**
     * 綁定服務
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new myControl();
    }

建立一箇中間類,來操做服務類方法。github

    /**
     * 中間類
     */
    public class myControl extends Binder {
    
       //  建立方法,可供其餘activity內調用
        public void mcontrol(String instructions) {
            // ....
        }
    }    

建立服務app

    /**
     * 建立服務
     */
    @Override
    public void onCreate() {
        super.onCreate();
        // ....建立服務時執行的方法
    }

開啓服務ide

    /**
     * 開啓服務
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

activity使用服務

在須要使用服務的activity文件的 onCreate 文件中引入服務並啓動this

        // 啓動服務
        Intent intent = new Intent(MainActivity.this, mService.class);
        startService(intent);
        conn = new mControl();
        // 綁定服務
        bindService(intent, conn, BIND_AUTO_CREATE);    

建立中間類,用來操做服務中的方法spa

    /**
     * 建立中間件對象
     */
    class mControl implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            control = (mService.myControl) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

當activity中須要調用服務中的方法時code

 control.mcontrol("31");

服務使用就是這樣。中間件

廣播的使用

發送廣播

        // 發送廣播
        Intent intent = new Intent();
        intent.putExtra("temValue", temValue);
        intent.setAction("mService");
        sendBroadcast(intent);    

接受廣播

在須要接受廣播的 activity 中註冊廣播監聽者對象

        // 註冊廣播監聽者
        receiver = new mReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("mService");
        MainActivity.this.registerReceiver(receiver, filter);

建立廣播監聽者內部類

    // 廣播監聽者
    public class mReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            temValue.setText(bundle.getString("temValue"));
        }
    }

 

廣播簡單的用法就這樣。

 案例:https://github.com/wjw1014/IntelligentMine/blob/master/app/src/main/java/com/example/admin/mine_feiyang/mService.java

相關文章
相關標籤/搜索