Android(安卓)service
1. 定义自已的service:
public class myService extends Service{
MediaPlayer player;
@Override
public IBinder onBind (Intent intent){
return null;
}
@Override
public void onCreate (){
Toast.makeText(this, "It is come from Service", Toast.LENGTH_LONG).show();
try{
player = new MediaPlayer();
player.setDataSource("//sdcard//44.mp3");
player.prepare();
}
catch (Exception e) {
Log.i("myService", e.toString());
}
}
@Override
public void onStart (Intent intent, int startId){
try{
player.start();
}
catch (Exception e) {
Log.i("myService", e.toString());
}
}
@Override
public void onDestroy (){
try{
Toast.makeText(this, "Stop", Toast.LENGTH_SHORT);
player.stop();
}
catch (Exception e) {
Log.i("myService", e.toString());
}
}
}
2. 注册Service:
<service android:enabled="true" android:name=".myService"/> in <application></application>
3. 启动Service 和停止:
Button start = (Button)findViewById(R.id.begin);
start.setOnClickListener(this);
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.begin:
startService(new Intent(this, myService.class));
break;
case R.id.stop:
stopService(new Intent(this, myService.class));
break;
}
}
进程之间
src
└── com
└── fly
├── IRemoteService.aidl
├── RemoteServiceActivity.java
└── RemoteService.java
IRemoteService.aidl
view plaincopy to clipboardprint?
- package com.fly;
- interface IRemoteService {
- int getCount();
- }
RemoteServiceActivity.java
view plaincopy to clipboardprint?
- package com.fly;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.os.RemoteException;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- public class RemoteServiceActivity extends Activity {
- private static final String TAG = "U0fly RemoteServiceActivity";
- private Button bnStart, bnStop;
- private TextView text1;
- private int count;
- private boolean isBound;
- private ServiceConnection serviceConnection = new ServiceConnection() {
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- // TODO Auto-generated method stub
- Log.d(TAG, "Start on Service Connected now");
- remoteService = IRemoteService.Stub.asInterface(service);
- try {
- Log.d(TAG, "on serivce connected, count is "
- + remoteService.getCount());
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
- }
- @Override
- public void onServiceDisconnected(ComponentName name) {
- // TODO Auto-generated method stub
- Log.d(TAG, "Start on Service Disconnected now");
- remoteService = null;
- }
- };
- private IRemoteService remoteService;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- this.bindService(new Intent(RemoteServiceActivity.this, RemoteService.class),
- this.serviceConnection, Context.BIND_AUTO_CREATE);
- Log.d(TAG, "Bind Service now");
- isBound = true;
- initUi();
- Log.d(TAG, "Init UI now");
- bnStart.setOnClickListener(new Button.OnClickListener() {
- public void onClick(View v) {
- try {
- text1.setText("Start Service now! count is :" + remoteService.getCount());
- } catch (RemoteException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- startService(new Intent(RemoteServiceActivity.this, RemoteService.class));
- Log.d(TAG, "Start Service now");
- }
- });
- bnStop.setOnClickListener(new Button.OnClickListener() {
- public void onClick(View v) {
- text1.setText("Stop Service now!");
- stopService(new Intent(RemoteServiceActivity.this, RemoteService.class));
- Log.d(TAG, "Stop Service now");
- }
- });
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- Log.d(TAG, "============> onDestroy");
- if (isBound) {
- this.unbindService(serviceConnection);
- isBound = false;
- }
- }
- public void initUi() {
- bnStart = (Button) findViewById(R.id.BnStart);
- bnStop = (Button) findViewById(R.id.BnStop);
- text1 = (TextView) findViewById(R.id.text1);
- }
- }
RemoteService.java
view plaincopy to clipboardprint?
- package com.fly;
- import android.app.Service;
- import android.content.Intent;
- import android.os.IBinder;
- import android.os.RemoteException;
- import android.util.Log;
- public class RemoteService extends Service {
- private static final String TAG = "U0fly RemoteService";
- private int count;
- private boolean threadDisable;
- private IRemoteService.Stub serviceBinder = new IRemoteService.Stub() {
- @Override
- public int getCount() throws RemoteException {
- // TODO Auto-generated method stub
- return count;
- }
- };
- @Override
- public IBinder onBind(Intent intent) {
- // TODO Auto-generated method stub
- Log.d(TAG, "============> onBind");
- return serviceBinder;
- }
- @Override
- public boolean onUnbind(Intent i) {
- Log.e(TAG, "============> onUnbind");
- return false;
- }
- @Override
- public void onRebind(Intent i) {
- Log.e(TAG, "============> onRebind");
- }
- @Override
- public void onCreate() {
- super.onCreate();
- Log.d(TAG, "============> onCreate");
- //TODO
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (!threadDisable) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- count++;
- Log.d(TAG, "Count is " + count);
- }
- }
- }).start();
- }
- @Override
- public void onStart(Intent intent, int startId) {
- Log.d(TAG, "============> onStart");
- /*
- // TODO
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (!threadDisable) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- count++;
- Log.d(TAG, "Count is " + count);
- }
- }
- }).start();*/
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- // TODO
- this.threadDisable = true;
- Log.d(TAG, "============> ondestroy");
- }
- public int getCount() {
- return count;
- }
- }
AndroidManifest.xml
view plaincopy to clipboardprint?
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.fly" android:versionCode="1" android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".RemoteServiceActivity"
- 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="RemoteService">
- <intent-fliter>
- <action android:name="com.fly.RemoteService" />
- </intent-fliter>
- </service>
- </application>
- <uses-sdk android:minSdkVersion="7" />
- </manifest>
更多相关文章
- Android(安卓)process与Thread 的问题
- android最近任务列表,删除某个应用操作
- 跨进程共享 SharedPreferences
- Android(安卓)kill app Process 结束进程代码
- android最近任务列表,删除某个应用操作
- Android(安卓)service: startService的代码实现
- Android高级进阶之路【六】Android(安卓)Framework解析
- Android中OnScrollListener回调具体剖析
- android 两个apk之间恭喜数据SharedPreferences