android service基础(1)

来源:互联网 发布:php contains 编辑:程序博客网 时间:2024/05/23 22:09

自定义service:

package com.example.services;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service{public static String TAG = "MyService";@Overridepublic IBinder onBind(Intent intent) {Log.w(TAG, "--myservice onbind--");return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.w(TAG, "--myservice onStartCommand--");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onCreate() {Log.w(TAG, "--myservice oncreate--");super.onCreate();}@Overridepublic void onDestroy() {Log.w(TAG, "-- myservice ondestroy--");super.onDestroy();}}


启动service的activity:

package com.example.servicedemo;import com.example.services.MyService;import android.app.Activity;import android.app.ActionBar;import android.app.Fragment;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.os.Build;public class MainActivity extends Activity {public static String TAG = "MyService";private Button startBtn;private Button endBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();setListener();}private void initView(){startBtn = (Button) findViewById(R.id.service_start_btn);endBtn = (Button) findViewById(R.id.service_end_btn);}private void setListener(){startBtn.setOnClickListener(startServiceListener);endBtn.setOnClickListener(endServiceListener);}OnClickListener startServiceListener = new OnClickListener() {@Overridepublic void onClick(View v) {Log.w(TAG, "-- serviceStartBtn clicked-- ");Intent intent = new Intent();intent.setClass(MainActivity.this, MyService.class);startService(intent);}};OnClickListener endServiceListener = new OnClickListener() {@Overridepublic void onClick(View v) {Log.w(TAG, "-- serviceEndBtn clicked-- ");Intent intent = new Intent(MainActivity.this,MyService.class);stopService(intent);}};@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}

这里用intent启动service的方式会调用service里的onStartCommand方法。



0 0
原创粉丝点击