Android之Service与Activity通信机制


android


关于Android之Service与Activity通信机制。

接下来研究下Service事件队列原理,待续。




0x01.Service生命周期

看一张网上的关于Service的生命周期

Service生命周期


Service主要包含本地类和远程类。

Service生命周期


Service主要在后台运行,我们可以在这里做网络状态监测,地理位置监测,以及系统状态监测等,然后通过broadcast广播,发送给前台进行处理。

Service不是Thread,Service 是android的一种机制,当它运行的时候如果是Local Service,那么对应的 Service 是运行在主进程的 main 线程上的。如:onCreate,onStart 这些函数在被系统调用的时候都是在主进程的 main 线程上运行的。如果是Remote Service,那么对应的 Service 则是运行在独立进程的 main 线程上。




0x02.Service的基本用法


启动service的方法很简单,首先在AndroidManifest.xml中注册才行。

<application  
    android:allowBackup="true"  
    android:icon="@drawable/ic_launcher"  
    android:label="@string/app_name"  
    android:theme="@style/AppTheme" >  
    <service android:name="me.homeway.servicebinder.MainService" >  
    </service>  
</application>


其次,要在Activity运行时候调用Intent对象生成Service。

Intent startIntent = new Intent(MainActivity.this, MainService.class);    
startService(startIntent); 


下面是service的基本调用方式,重写onCreate()、onStartCommand()和onDestroy()方法。

onCreate()只启动一次,onStartCommand()会在每次启动activity时候运行,onDestroy()只在service关闭时候运行。

public class MainService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

0x03.Service通过IBinder与Activity通信

下面是主要源码。

MainService.java

public class MainService extends Service{

    private String TAG = "MainService";
    public ServiceBinder mBinder = new ServiceBinder(); /* 数据通信的桥梁 */

    /* 重写Binder的onBind函数,返回派生类 */
    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    @Override
    public void onCreate() {    
        Toast.makeText( MainService.this, "Service Create...", Toast.LENGTH_SHORT).show();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(MainService.this, "Service StartCommand", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {    
            Toast.makeText( MainService.this, "Service Destroy", Toast.LENGTH_SHORT).show();
    }

    /* 第一种模式通信:Binder */
    public class ServiceBinder extends Binder { 

        public void startDownload() throws InterruptedException {  
            /* 模拟下载,休眠2秒 */
            Toast.makeText( MainService.this, "模拟下载2秒钟,开始下载...", Toast.LENGTH_SHORT).show();
            Thread.sleep(2);
            Toast.makeText( MainService.this, "下载结束...", Toast.LENGTH_SHORT).show();
        }
    }
}


MainActivity.java

public class MainActivity extends Activity {
    /* 通过Binder,实现Activity与Service通信 */
    private MainService.ServiceBinder mBinderService;
    private ServiceConnection connection = new ServiceConnection() {  
        @Override  
        public void onServiceDisconnected(ComponentName name) {  
        }  

        @Override  
        public void onServiceConnected(ComponentName name, IBinder service) {  
            mBinderService = (MainService.ServiceBinder) service;
            try {
                mBinderService.startDownload();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }  
        }  
    };

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

        Intent bindIntent = new Intent(MainActivity.this, MainService.class);  
        bindService(bindIntent, connection, BIND_AUTO_CREATE); 
    }
}    




0x04.Service通过BroadCast广播与Activity通信

关于广播的原理。

Android 广播原理


MainService.java

public class MainService extends Service{

    private String TAG = "MainService";
    public ServiceBinder mBinder = new ServiceBinder(); /* 数据通信的桥梁 */

    /* 重写Binder的onBind函数,返回派生类 */
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {    
        Toast.makeText( MainService.this, "Service Create, Send BroadCast...", Toast.LENGTH_SHORT).show();
        SendServiceBroadCast();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(MainService.this, "Service StartCommand", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {    
            Toast.makeText( MainService.this, "Service Destroy", Toast.LENGTH_SHORT).show();
    }

    /* 第二种模式通信:Broadcast广播 */
    public void SendServiceBroadCast() throws InterruptedException {  
        Log.d(TAG, "ServiceThread===>>startDownload() executed===>>线程ID:"+Thread.currentThread().getId());  
        Toast.makeText( MainService.this, "Send BroadCast now...", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
            intent.setAction("me.homeway.servicebinder.BroadcastTest");
            intent.putExtra("value", 1000);
            sendBroadcast(intent);
            Toast.makeText( MainService.this, "Sent! Did you receive?", Toast.LENGTH_SHORT).show();
    }
}


新建一个类,命名成 BroadcastTest.java 放在 me.homeway.servicebinder 包里面。

这里我们使用静态注册方式,所以要在AndroidManifest.xml中注册广播。

AndroidManifest.xml


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">

    <receiver android:name=".BroadcastTest">
        <intent-filter>
            <action android:name="me.homeway.servicebinder.BroadcastTest"></action>
        </intent-filter>
    </receiver>
    ...    
</application>


BroadcastTest.java

public class BroadcastTest extends BroadcastReceiver{

    private NetworkInfo netInfo;
    private ConnectivityManager mConnectivityManager;

    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if(extras.containsKey("value")){
                /* 这里可以做下载,发包等事件 */
                Toast.makeText( context, "收到广播 => "+extras.get("value"), Toast.LENGTH_SHORT).show();
                System.out.println("Value is:"+extras.get("value"));
            }
        }      
       }
}


效果图
效果图




0x05.参考

0x01. http://www.vogella.com/tutorials/AndroidServices/article.html

0x02.http://blog.csdn.net/guolin_blog/article/details/11952435

0x03.http://www.tutorialspoint.com/android/android_services.htm




0x06.送福利

关于程序问题,欢迎联系我。xiaocao.grasses@gmail.com

源码下载这里: ServiceBinder.zip

APK下载:ServiceBinder.apk




本文出自 夏日小草,转载请注明出处:http://homeway.me/2014/12/02/android-service-share-data-with-activity/


-by小草

2014-12-02 01:27:34

Fork me on GitHub