APP
MainActivity.java
package com.xfeng.startservicefromanotherapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //启动服务 startService(new Intent(this,AppService.class)); } @Override protected void onDestroy() { super.onDestroy(); //停止服务 stopService(new Intent(this,AppService.class)); } }
AppService.java
package com.xfeng.startservicefromanotherapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import java.sql.SQLOutput; public class AppService extends Service { public AppService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); System.out.println("Service started"); } @Override public void onDestroy() { super.onDestroy(); System.out.println("Service destory"); } }
AnotherApp
package com.xfeng.anotherapp; import android.content.ComponentName; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Intent serviceIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serviceIntent = new Intent(); //显示intent serviceIntent.setComponent(new ComponentName("com.xfeng.startservicefromanotherapp", "com.xfeng.startservicefromanotherapp.AppService")); findViewById(R.id.btnStartAppService).setOnClickListener(this); findViewById(R.id.btnStopAppService).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnStartAppService: // Intent i = new Intent(); // //显示intent // i.setComponent(new ComponentName("com.xfeng.startservicefromanotherapp","com.xfeng.startservicefromanotherapp.AppService")); startService(serviceIntent); break; case R.id.btnStopAppService: stopService(serviceIntent); break; } } }
时间: 2024-10-25 06:07:40