BindServiceDemo

本文介绍了一个简单的Android应用案例,该应用通过绑定服务的方式实现下载进度的实时更新。MainActivity通过绑定MsgService服务并监听下载进度,进而更新进度条。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



MainActivity.java

public class MainActivity extends Activity {  

    private MsgService msgService;  
    private int progress = 0;  
    private ProgressBar mProgressBar;  
      
 
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        msgService = new MsgService();
          
        //绑定Service  
        Intent intent = new Intent("com.example.MSG_ACTION");  
        bindService(intent, conn, Context.BIND_AUTO_CREATE);  
          
          
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
        Button mButton = (Button) findViewById(R.id.button1);  
        mButton.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View v) {  
                //开始下载  
                msgService.startDownLoad();  
                //监听进度  
                listenProgress();  
            }  
        });  
          
    }  
      
 
    /**
     * 监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI
     */  
    public void listenProgress(){  
        new Thread(new Runnable() {  
              
            @Override  
            public void run() {  
                while(progress < MsgService.MAX_PROGRESS){  
                    progress = msgService.getProgress();  
                    mProgressBar.setProgress(progress);  
                    try {  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
                  
            }  
        }).start();  
    }  
      
    ServiceConnection conn = new ServiceConnection() {  
        @Override  
        public void onServiceDisconnected(ComponentName name) {  
              
        }  
          
        @Override  
        public void onServiceConnected(ComponentName name, IBinder service) {  
            //返回一个MsgService对象  
            msgService = ((MsgService.MsgBinder)service).getService();  
              
        }  
    };  
 
    @Override  
    protected void onDestroy() {  
        unbindService(conn);  
        super.onDestroy();  
    }  
 

}


MsgService.java

public class MsgService extends Service {

    /**
     * 进度条的最大值
     */  
    public static final int MAX_PROGRESS = 100;  
    /**
     * 进度条的进度值
     */  
    private int progress = 0;  
 
    /**
     * 增加get()方法,供Activity调用
     * @return 下载进度
     */  
    public int getProgress() {  
        return progress;  
    }  
 
    /**
     * 模拟下载任务,每秒钟更新一次
     */  
    public void startDownLoad(){  
        new Thread(new Runnable() {  
              
            @Override  
            public void run() {  
                while(progress < MAX_PROGRESS){  
                    progress += 5;  
                    try {  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                      
                }  
            }  
        }).start();  
    }  
 
 
    /**
     * 返回一个Binder对象
     */  
    @Override  
    public IBinder onBind(Intent intent) {  
        return new MsgBinder();  
    }  
      
    public class MsgBinder extends Binder{  
        /**
         * 获取当前Service的实例
         * @return
         */  
        public MsgService getService(){  
            return MsgService.this;  
        }  
    }

}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="开始下载"/>

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal" />

</LinearLayout>



AndroidMainfest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bindservicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bindservicedemo.MainActivity"
            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=".MsgService"></service>
    </application>

</manifest>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值