分享

【转】Android Service与Runnable整合并用

 techres 2012-02-09

Android Service与Runnable整合并用

服务的启动没有Activity,即便是利用Activity带起服务,也会有各看成独立的事件及焦点要处理。

Service继承自Android.app.Service。

服务的生态链就先从onCreate()开始(如果有重写的话) ,接着应会进入启动服务onStart(),默认继承的Service类,并不一定要有onStart(),但是一定要重写public IBinder onBind(Intent intent)方法。

 package cn.iimob;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class demo extends Activity {
    private Button btnStartService,btnStopService;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartService=(Button)findViewById(R.id.btnStartService);
        btnStopService=(Button)findViewById(R.id.btnStopService);
        btnStartService.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                //构建 Intent 对象,指定打开对象为 MyService服务
                Intent i=new Intent(demo.this, MyService.class);
                //设置新Task的方式
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //以startService 方法启动 Intent
                startService(i);
            }
        });
        btnStopService.setOnClickListener(new Button.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // 构建 Intent对象,指定关闭的对象为MyService服务
                Intent i=new Intent(demo.this, MyService.class);
                
                //以stopService 方法关闭 Intent
                stopService(i);
            }
        });
    }
}

 package cn.iimob;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 *  @Project       : servicedemo
 *  @Program Name  : cn.iimob.MyService.java
 *  @Class Name    : MyService
 *  @Description   : 自定义 MyService 类继承 Service 类
 *  @Author        : zh
 *  @Creation Date : 2011-11-3 上午09:49:00 
 *  @ModificationHistory  
 *  Who        When          What 
 *  --------   ----------    -----------------------------------
 *  username   2011-11-3       TODO
 
*/
public class MyService extends Service {

    /**
     * 创建 Handler 对象,作为进程 传递 postDelayed 之用
     
*/
    private Handler myhandler = new Handler();
    
    /**
     * 为了确认系统服务运行情况
     
*/
    private int intCounter=0;
    
    /**
     * 成员变量 myTasks为Runnable对象,作为Timer之用
     
*/
    private Runnable myTasks=new Runnable() {
        /**
         * 进程运行
         
*/
        @Override
        public void run() {
            // TODO Auto-generated method stub
            
//递增counter整数,作为后台服务运行时间识别
            intCounter++;
            //以Log 对象在LogCat 里输出Log信息,监看服务运行情况
            Log.i("Run Service", "Counter:"+Integer.toString(intCounter));
            myhandler.postDelayed(myTasks, 1000);
        }
    };
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onStart(Intent intent,int startId){
        myhandler.postDelayed(myTasks, 1000);
        super.onStart(intent, startId);
        Log.i("Start Service", "onStart");
    }
    
    @Override
    public void onCreate(){
        super.onCreate();
        Log.i("Create Service", "onCreate");
    }
    
    @Override
    public void onDestroy(){
        //当服务结束,删除 mTasks 运行线程 
        myhandler.removeCallbacks(myTasks);
        super.onDestroy();
        Log.i("Destroy Service", "onDestroy");
    }
    
    
}

 

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas./apk/res/android"
    android:orientation
="vertical"
    android:layout_width
="fill_parent"
    android:layout_height
="fill_parent"
    
>
<TextView  
    
android:layout_width="fill_parent" 
    android:layout_height
="wrap_content" 
    android:text
="@string/hello"
    
/>
<Button android:text="开始Service" android:id="@+id/btnStartService" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="终止Service" android:id="@+id/btnStopService" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

 

 <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas./apk/res/android"
      package
="cn.iimob"
      android:versionCode
="1"
      android:versionName
="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".demo"
                  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:exported属情为true,表示此服务可被其他程序访问  -->
        <service android:name=".MyService" android:exported="true" android:process=":remote"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest> 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多