当前位置:操作系统 > 安卓/Android >>

Android下Service入门

Service做为Android的5个基本组件之一,是很强大的,实现基本功能也并不复杂

Android下做个木马的话 用服务实现,是必须的,它可以后台运行,开始启动,下面实现简单的

1.在Eclipse中创建一个新的Android工程 HelloService

2.在ServiceAndroid项目->New->Class Package选择ServiceAndroid Name写MyService

3.打开MyService.java 输入如下内容

package Service.HelloService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
    private boolean threadDisable;
    private int count;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    count++;
                    Log.v("MyService", "Count is " + count);
                }
            }
        }).start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("CountService", "on destroy");
    }
    public int getCount() {
        return count;
    }
}

4.修改 项目的 AndroidManifest.xml文件 加入一句 注册服务

<service android:name="MyService" />

5.修改项目主文件Service.java代码如下

package Service.HelloService;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
public class Service extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.startService(new Intent(this, MyService.class));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.stopService(new Intent(this, MyService.class));
    }
}
 

现在就完成了,开始编译 运行 Android模拟器出现后 打开LogCat 就可以看到调试的信息了

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,