android 服务和进程

2017-06-08  本文已影响0人  yanghanbin_it

进程

  1. Foreground process 前台进程
    • 拥有一个正在与用户交互的Activity(onResume方法被调用)的进程
    • 拥有一个与正在与用户交互的Activity绑定的服务进程
    • 拥有一个正在"运行于前台"的服务(服务的startforground方法被调用)
    • 拥有一个正在执行以下三个周期方法任意一个方法的服务(onCreate onStart onDestroy)
    • 拥有一个正在执行onReceive方法的广播接收者进程
  2. Visible process 可见进程
    • 拥有一个可见但是没有获得焦点的Acitivity(onPause方法被调用)的进程
    • 拥有一个与可见activity绑定的服务的进程
  3. service process 拥有一个通过startService方法启动的服务
  4. background process 后台进程 拥有一个不可见的activity(onStop方法被调用)的进程
  5. empty process 空进程 没有拥有任何活动的应用组件的进程

服务 service

运行于后台的一个组件,用来运行合适运行在后台的代码,服务是没有前台界面,可以视为没有界面的Activity。

public class MainActivity extends AppCompatActivity {

    Intent intent;

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

        //显示启动服务
        intent = new Intent(this, MyService.class);
    }

    /**
     * 开启服务
     *
     * @param v
     */
    public void click(View v) {
        startService(intent);
    }


    /**
     * 关闭服务
     *
     * @param v
     */
    public void click2(View v) {
        stopService(intent);
    }
}

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println();
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand 方法");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        System.out.println("onDestroy 方法");
        super.onDestroy();
    }

    @Override
    public void onCreate() {
        System.out.println("onCreate 方法");
        super.onCreate();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读