Go

AndroidManifest.xml

        <service android:name=".MyIntentService"></service>

MyIntentService.java

override onHandleIntent , use intent check any task.

intent getExtra get task key

public class MyIntentService extends IntentService {

    private static final String TAG = MyIntentService.class.getSimpleName();
    public static final String ACTION_DONE = "Service Done";

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String intentString = intent.getStringExtra("NAME");
        Log.d(TAG, "onHandleIntent: " + intentString);

        for (int i = 0 ; i<5 ; i++){
            SystemClock.sleep(1000);
            Log.d(TAG, "onHandleIntent: start "+ i);
        }
        Log.d(TAG, "onHandleIntent: done");

        Intent intent1 = new Intent();
        intent1.setAction(ACTION_DONE);
        sendBroadcast(intent1);


    }
}

MainActivity.java

  1. registerReceiver broadcast , filter is get target Action
  2. startService void , putExtra is put task key
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

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

        IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION_DONE);
        registerReceiver(receiver,intentFilter);


    }
    public void startIntentService(View v){
        Intent intent = new Intent(this,MyIntentService.class);
        intent.putExtra("NAME","T1");
        startService(intent);
        intent.putExtra("NAME","T2");
        startService(intent);
        intent.putExtra("NAME","T3");
        startService(intent);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: "+intent.getAction());
        }
    };
}

Code

https://github.com/encorex32268/blogthing/tree/master/TestIntentService/app/src/main/java/com/lee/testintentservice

Result

最後修改日期: 2019-04-30 18:54:42

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料