溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android中IntentService如何使用

發(fā)布時間:2021-06-26 16:26:05 來源:億速云 閱讀:219 作者:Leah 欄目:移動開發(fā)

本篇文章為大家展示了android中IntentService如何使用,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

服務的簡單說明

一、 前臺服務與IntentService:

前臺服務可以一直保持運行狀態(tài),而不會由于系統(tǒng)內(nèi)存不足的原因?qū)е卤换厥?br/>

service服務測試的準備代碼

我們通過一個具體的案例來說明start與bind方式的service服務的生命周期的介紹。項目結(jié)果如下:

android中IntentService如何使用

一、 在MainActivity.java中做一些初始化工作,如下代碼:

private final static String TAG = "MyIntentService";  private MyIntentService.MyBinder binder;   private ServiceConnection connection = new ServiceConnection() {      @Override      public void onServiceConnected(ComponentName name, IBinder service) {          binder = (MyIntentService.MyBinder) service;          binder.sayHello(name.getClassName());      }       @Override      public void onServiceDisconnected(ComponentName name) {          Log.i(TAG, "service disconnect: " + name.getClassName());      }  };   @Override  protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_main);  }

二、 創(chuàng)建一個簡單的IntentService服務類:MyIntentService

package com.example.linux.intentservicetest;   import android.app.IntentService;  import android.content.Intent;  import android.os.Binder;  import android.os.IBinder;  import android.util.Log;   public class MyIntentService extends IntentService {      private final static String TAG = "MyIntentService";      private MyBinder myBinder = new MyBinder();       class MyBinder extends Binder {          public void sayHello(String name) {              Log.i(TAG, "say hello method: " + name);          }           public void sayWorld(String name) {              Log.i(TAG, "say world method: " + name);          }      }       @Override      public IBinder onBind(Intent intent) {          return myBinder;      }       public MyIntentService() {          super("MyIntentService");          Log.i(TAG, "myintent service constructor.");      }       @Override      public void onCreate() {          Log.i(TAG, "on create.");          super.onCreate();      }       @Override      protected void onHandleIntent(Intent intent) {          Log.i(TAG, "handle intent: " + intent.getStringExtra("username") + ", thread: " + Thread.currentThread());      }       @Override      public void onDestroy() {          super.onDestroy();          Log.i(TAG, "on destroy.");      }       @Override      public int onStartCommand(Intent intent, int flags, int startId) {          Log.i(TAG, "on start command.");          return super.onStartCommand(intent, flags, startId);      }       @Override      public boolean onUnbind(Intent intent) {          //默認返回false          String username = intent.getStringExtra("username");          Log.i(TAG, "on unbind: " + super.onUnbind(intent) + ", username: " + username);          return true;      }       @Override      public void onRebind(Intent intent) {          Log.i(TAG, "on rebind");          super.onRebind(intent);      }  }

三、 創(chuàng)建一個簡單的前臺服務類:FrontService

package com.example.linux.intentservicetest;   import android.app.Notification;  import android.app.PendingIntent;  import android.app.Service;  import android.content.Intent;  import android.os.IBinder;  import android.util.Log;   public class FrontService extends Service {      private final static String TAG = "MyIntentService";      public FrontService() {          Log.i(TAG, "front service constructor");      }       @Override      public IBinder onBind(Intent intent) {          return null;      }       @Override      public void onCreate() {          super.onCreate();          Notification.Builder builder = new Notification.Builder(this);          Intent intent = new Intent(this, MainActivity.class);          PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,                  PendingIntent.FLAG_CANCEL_CURRENT);           builder.setSmallIcon(R.mipmap.ic_launcher).setTicker("ticker");          builder.setWhen(System.currentTimeMillis()).setAutoCancel(true);          builder.setContentTitle("content title").setContentText("content text");          builder.setContentIntent(pendingIntent);           Notification notify = builder.getNotification();           notify.defaults = Notification.DEFAULT_ALL;          startForeground(10, notify);      }  }

四、 在AndroidManifest.xml中注冊服務與活動

<activity android:name=".MainActivity">      <intent-filter>          <action android:name="android.intent.action.MAIN" />          <category android:name="android.intent.category.LAUNCHER" />      </intent-filter>  </activity>   <service      android:name=".MyIntentService"     android:exported="false">  </service>  <service      android:name=".FrontService"     android:enabled="true"     android:exported="true">  </service>

Intent服務的使用

一、 在MainActivity中創(chuàng)建方法,啟動停止服務:

// 開啟服務  public void startService(View view) {      Intent intent = new Intent();      intent.putExtra("username", "linux");      intent.setClass(MainActivity.this, MyIntentService.class);      startService(intent);  }   // 停止服務  public void stopService(View view) {      Intent intent = new Intent();      intent.setClass(MainActivity.this, MyIntentService.class);      stopService(intent);  }

二、 在MainActivity中創(chuàng)建方法,綁定解綁服務:

// 綁定服務  public void bindService(View view) {      Intent intent = new Intent();      intent.setClass(MainActivity.this, MyIntentService.class);      intent.putExtra("username", "linux");      boolean isBind = bindService(intent, connection, Context.BIND_AUTO_CREATE);      Log.i(TAG, "bind service: " + isBind);  }   // 解綁服務  public void unbindService(View view) {      Intent intent = new Intent();      intent.setClass(MainActivity.this, MyIntentService.class);      unbindService(connection);  }

三、 運行結(jié)果

點擊start:

03-25 08:01:53.460 8389-8389/? I/MyIntentService: myintent service constructor.  03-25 08:01:53.460 8389-8389/? I/MyIntentService: on create.  03-25 08:01:53.475 8389-8389/? I/MyIntentService: on start command.  03-25 08:01:53.477 8389-8727/? I/MyIntentService: handle intent: linux, thread: Thread[IntentService[MyIntentService],5,main]  03-25 08:01:53.478 8389-8389/? I/MyIntentService: on destroy.


點擊stop:無輸出
點擊bind:

03-25 08:02:25.421 8389-8389/? I/MyIntentService: bind service: true 03-25 08:02:25.422 8389-8389/? I/MyIntentService: myintent service constructor.  03-25 08:02:25.422 8389-8389/? I/MyIntentService: on create.  03-25 08:02:25.432 8389-8389/? I/MyIntentService: say hello method: com.example.linux.intentservicetest.MyIntentService

點擊unbind:

03-25 08:02:28.486 8389-8389/? I/MyIntentService: on unbind: false, username: linux  03-25 08:02:28.490 8389-8389/? I/MyIntentService: on destroy.

前臺服務的使用

一、 在MainActivity中創(chuàng)建方法,啟動前臺服務:

// 前臺服務的使用  public void frontService(View view) {      Intent intent = new Intent();      intent.setClass(MainActivity.this, FrontService.class);      startService(intent);  }

二、 運行結(jié)果: 在手機的通知欄中

android中IntentService如何使用

IntentService的原理分析

一、 intentService是繼承Service的抽象方法

public abstract class IntentService extends Service

二、 intentService包含的一些字段引用如下

private volatile Looper mServiceLooper;  private volatile ServiceHandler mServiceHandler;  private String mName;  private boolean mRedelivery;   private final class ServiceHandler extends Handler {      public ServiceHandler(Looper looper) {          super(looper);      }       @Override      public void handleMessage(Message msg) {          onHandleIntent((Intent)msg.obj);          stopSelf(msg.arg1);      }  }

二、 和service一樣在啟動的時候,首先是執(zhí)行構(gòu)造方法,接著是onCreate方法,然后是onStartCommand方法,在onStartCommand中執(zhí)行了onStart方法(執(zhí)行流程在android基礎(chǔ)---->service的生命周期講過):

onCreate方法,開啟了一個線程,并且得到Looper與初始化了一個Handler

@Override  public void onCreate() {      // TODO: It would be nice to have an option to hold a partial wakelock      // during processing, and to have a static startService(Context, Intent)      // method that would launch the service & hand off a wakelock.       super.onCreate();      HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");      thread.start();       mServiceLooper = thread.getLooper();      mServiceHandler = new ServiceHandler(mServiceLooper);  }

onStart方法,用上述的Handler發(fā)送信息

@Override  public void onStart(Intent intent, int startId) {      Message msg = mServiceHandler.obtainMessage();      msg.arg1 = startId;      msg.obj = intent;      mServiceHandler.sendMessage(msg);  }

onStartCommand方法,調(diào)用onStart方法,發(fā)送信息

@Override  public int onStartCommand(Intent intent, int flags, int startId) {      onStart(intent, startId);      return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;  }


***上述的Handler得到信息,調(diào)用handleMessage方法,其中有stopSelf(msg.arg1)方法,停止了服務:

三、 這里附上service類的兩個方法,源代碼是android6.0的

在Service中的onStart方法已經(jīng)被廢棄了:

/**   * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.  */ @Deprecated  public void onStart(Intent intent, int startId) {  }

在onStartCommand的方法中

public int onStartCommand(Intent intent, int flags, int startId) {      onStart(intent, startId);      return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;  }

上述內(nèi)容就是android中IntentService如何使用,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI