Skip to content

Instantly share code, notes, and snippets.

@XjojoX1989
XjojoX1989 / launchMode.xml
Last active June 26, 2019 08:56
android manifest
<activity android:name=".Project"
android:launchMode="standard"||"singleTop"||"singleInstance"||"singleTask"/>
<activity android:name=".activity"
android:launchMode="singleTop"/>
<activity android:name=".activity"
android:launchMode="singleTask"/>
<activity android:name=".activity"
android:launchMode="singleInstance"/>
<service android:name=".MyService"/>
public class MyService : Service() {
//啟動或bind這個service元件時,第一個呼叫的方法
override fun onCreate() {
Log.e("***", "onCreate")
}
//啟動service元件時呼叫的方法
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e("***", "onStartCommand")
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btService).setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("test", "test service");
class MyService : Service(){
override fun onBind(intent: Intent?): IBinder? {
Log.e(TAG, "onBind")
return MyBinder()
}
inner class MyBinder : Binder(){
}
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
//此時已在背景執行緒了,可以開始耗時操作
}
override fun onDestroy() {
super.onDestroy()
}
}
public class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById(R.id.btIntentService).setOnClickListener{
//啟動IntentService
startService(new Intent(MainActivity.this, MyIntentService.class));
}
}