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?

  1. package com.fly; 
  2. interface IRemoteService { 
  3. int getCount(); 

RemoteServiceActivity.java

view plaincopy to clipboardprint?

  1. package com.fly; 
  2. import android.app.Activity; 
  3. import android.content.ComponentName; 
  4. import android.content.Context; 
  5. import android.content.Intent; 
  6. import android.content.ServiceConnection; 
  7. import android.os.Bundle; 
  8. import android.os.IBinder; 
  9. import android.os.RemoteException; 
  10. import android.util.Log; 
  11. import android.view.View; 
  12. import android.widget.Button; 
  13. import android.widget.TextView; 
  14. public class RemoteServiceActivity extends Activity { 
  15. private static final String TAG = "U0fly RemoteServiceActivity"; 
  16. private Button bnStart, bnStop; 
  17. private TextView text1; 
  18. private int count; 
  19. private boolean isBound; 
  20. private ServiceConnection serviceConnection = new ServiceConnection() { 
  21. @Override
  22. public void onServiceConnected(ComponentName name, IBinder service) { 
  23. // TODO Auto-generated method stub
  24.             Log.d(TAG, "Start on Service Connected now"); 
  25.             remoteService = IRemoteService.Stub.asInterface(service); 
  26. try { 
  27.                 Log.d(TAG, "on serivce connected, count is "
  28.                         + remoteService.getCount()); 
  29.             } catch (RemoteException e) { 
  30. throw new RuntimeException(e); 
  31.             } 
  32.         } 
  33. @Override
  34. public void onServiceDisconnected(ComponentName name) { 
  35. // TODO Auto-generated method stub
  36.             Log.d(TAG, "Start on Service Disconnected now"); 
  37.             remoteService = null; 
  38.         } 
  39.     }; 
  40. private IRemoteService remoteService; 
  41. /** Called when the activity is first created. */
  42. @Override
  43. public void onCreate(Bundle savedInstanceState) { 
  44. super.onCreate(savedInstanceState); 
  45.         setContentView(R.layout.main); 
  46. this.bindService(new Intent(RemoteServiceActivity.this, RemoteService.class), 
  47. this.serviceConnection, Context.BIND_AUTO_CREATE); 
  48.         Log.d(TAG, "Bind Service now"); 
  49.         isBound = true; 
  50.         initUi(); 
  51.         Log.d(TAG, "Init UI now"); 
  52.         bnStart.setOnClickListener(new Button.OnClickListener() { 
  53. public void onClick(View v) { 
  54. try { 
  55.                     text1.setText("Start Service now! count is :" + remoteService.getCount()); 
  56.                 } catch (RemoteException e) { 
  57. // TODO Auto-generated catch block
  58.                     e.printStackTrace(); 
  59.                 } 
  60.                 startService(new Intent(RemoteServiceActivity.this, RemoteService.class)); 
  61.                 Log.d(TAG, "Start Service now"); 
  62.             } 
  63.         }); 
  64.         bnStop.setOnClickListener(new Button.OnClickListener() { 
  65. public void onClick(View v) { 
  66.                 text1.setText("Stop Service now!"); 
  67.                 stopService(new Intent(RemoteServiceActivity.this, RemoteService.class)); 
  68.                 Log.d(TAG, "Stop Service now"); 
  69.             } 
  70.         }); 
  71.     } 
  72. @Override
  73. protected void onDestroy() { 
  74. super.onDestroy(); 
  75.         Log.d(TAG, "============> onDestroy"); 
  76. if (isBound) { 
  77. this.unbindService(serviceConnection); 
  78.             isBound = false; 
  79.         } 
  80.     } 
  81. public void initUi() { 
  82.         bnStart = (Button) findViewById(R.id.BnStart); 
  83.         bnStop = (Button) findViewById(R.id.BnStop); 
  84.         text1 = (TextView) findViewById(R.id.text1); 
  85.     } 

RemoteService.java

view plaincopy to clipboardprint?

  1. package com.fly; 
  2. import android.app.Service; 
  3. import android.content.Intent; 
  4. import android.os.IBinder; 
  5. import android.os.RemoteException; 
  6. import android.util.Log; 
  7. public class RemoteService extends Service { 
  8. private static final String TAG = "U0fly RemoteService"; 
  9. private int count; 
  10. private boolean threadDisable; 
  11. private IRemoteService.Stub serviceBinder = new IRemoteService.Stub() { 
  12. @Override
  13. public int getCount() throws RemoteException { 
  14. // TODO Auto-generated method stub
  15. return count; 
  16.         } 
  17.     }; 
  18. @Override
  19. public IBinder onBind(Intent intent) { 
  20. // TODO Auto-generated method stub
  21.         Log.d(TAG, "============>  onBind"); 
  22. return serviceBinder; 
  23.     } 
  24. @Override
  25. public boolean onUnbind(Intent i) { 
  26.         Log.e(TAG, "============>  onUnbind"); 
  27. return false; 
  28.     } 
  29. @Override
  30. public void onRebind(Intent i) { 
  31.         Log.e(TAG, "============>  onRebind"); 
  32.     } 
  33. @Override
  34. public void onCreate() { 
  35. super.onCreate(); 
  36.         Log.d(TAG, "============>  onCreate"); 
  37. //TODO
  38. new Thread(new Runnable() { 
  39. @Override
  40. public void run() { 
  41. while (!threadDisable) { 
  42. try { 
  43.          Thread.sleep(1000); 
  44.          } catch (InterruptedException e) { 
  45.          } 
  46.          count++; 
  47.          Log.d(TAG, "Count is " + count); 
  48.          } 
  49.          } 
  50.          }).start(); 
  51.     } 
  52. @Override
  53. public void onStart(Intent intent, int startId) { 
  54.         Log.d(TAG, "============> onStart"); 
  55. /*
  56.         // TODO
  57.         new Thread(new Runnable() {
  58.             @Override
  59.             public void run() {
  60.                 while (!threadDisable) {
  61.                     try {
  62.                         Thread.sleep(1000);
  63.                     } catch (InterruptedException e) {
  64.                     }
  65.                     count++;
  66.                     Log.d(TAG, "Count is " + count);
  67.                 }
  68.             }
  69.         }).start();*/
  70.     } 
  71. @Override
  72. public void onDestroy() { 
  73. super.onDestroy(); 
  74. // TODO
  75. this.threadDisable = true; 
  76.         Log.d(TAG, "============>  ondestroy"); 
  77.     } 
  78. public int getCount() { 
  79. return count; 
  80.     } 

AndroidManifest.xml

view plaincopy to clipboardprint?

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.fly" android:versionCode="1" android:versionName="1.0"> 
  4.     <application android:icon="@drawable/icon" android:label="@string/app_name"> 
  5.         <activity android:name=".RemoteServiceActivity"
  6.             android:label="@string/app_name"> 
  7.             <intent-filter> 
  8.                 <action android:name="android.intent.action.MAIN" /> 
  9.                 <category android:name="android.intent.category.LAUNCHER" /> 
  10.             </intent-filter> 
  11.         </activity> 
  12.         <service android:name="RemoteService"> 
  13.             <intent-fliter> 
  14.                 <action android:name="com.fly.RemoteService" /> 
  15.             </intent-fliter> 
  16.         </service> 
  17.     </application> 
  18.     <uses-sdk android:minSdkVersion="7" /> 
  19. </manifest>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值