首先创建一个接口
public interface MyActions {
public void doActions();
}
现在让您的服务类实现该接口
public class MyService extends Service implements MyActions{
并覆盖该方法
@Override
public void doActions() {
//Some code
}
现在您的活动 A 正在通过 startActivityForResult 方法调用 B,因此覆盖 A 的 onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Some code
}
现在在这个 A 类中创建接口的静态实例
static MyActions mActions;
现在写一个像这样的静态方法
public static void setMyListener(MyActions act){
mActions = act;
}
现在在您为 A 类覆盖的 onActivityResult 中添加这行代码
mActions.doActions();
所以你得到
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mActions.doActions();
}
现在在 onStart() 方法中的 Service 类中,在调用活动之前写下这一行
ActA.setMyListener(this);
现在就完成了,当从 Activity B 调用转到 A 的 onActivityResult 并且从 A 服务可以侦听 doActions() 的覆盖方法时
将所有代码写入您想要执行的服务的 doActions() 方法中
这是代码
第一个活动:ActA.java
public class ActA extends Activity {
static MyActions mActions;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.act1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(ActA.this,ActB.class), 15);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Response","requestCode" + requestCode + " resultCode" + resultCode);
mActions.doActions();
}
public static void setMyListener(MyActions act){
mActions = act;
}
}
第二个活动:ActB.java
public class ActB extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
}
}
应用启动时的 MainActivity
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Start the service
startService(new Intent(this, MyService.class));
}
}
接口:MyActions.java
public interface MyActions {
public void doActions();
}
服务类:MyService.java
public class MyService extends Service implements MyActions{
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("Response", "Started");
ActA.setMyListener(this);
startActivity(new Intent(this,ActA.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
@Override
public void doActions() {
Log.d("Response", "Listener working");
}
}