Service如何关闭启动自己的Activity
今天在编写Android程序的时候,遇到这个问题。通过百度和google的搜索结果,总结出以下方法:
方法一:
public class mService extends Service {
//保存在service中的Activity对象
private static mActivity m;
//启动服务
static void
startservice(Context c){
m=(mActivity)c;
Intent iService=new Intent(c,mService.class);
iService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(iService);
}
//关闭服务
static void
stopservice(Context c){
Intent iService=new Intent(c,mService.class);
iService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.stopService(iService);
}
……
//在mService中关闭mActivity
m.finish();
}
public class mActivity extends Activity {
// private MediaPlayer mMPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
……
//启动mService
mService.
start
service(mActivity.this);
……
//停止mService
mService.stopservice(mActivity.this);
}
}
方法二:
主要包括3部分
1. 定义application类,这个类可以保存获取activity实例,记得manifest中加入android:name=".MyApp"
public class MyApp extends Application{
private MyServiceActivity myActivity;
public void
setInstance(MyServiceActivity instance){
myActivity = instance;
}
public MyServiceActivity
getInstance(){
return myActivity;
}
}
2. 在activity中保存实例
public class MyServiceActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApp)getApplication()).setInstance(this);
……
}
}
3. 在service中取回实例
public class MyService extends Service {
MyServiceActivity myActivity;
@Override
public void onCreate() {
super.onCreate();
setForeground(true);
android.os.Debug.waitForDebugger();
myActivity = ((MyApp)getApplication()).getInstance();
……
}
}
方法一:
public class mService extends Service {
}
public class mActivity extends Activity {
}
方法二:
主要包括3部分
1. 定义application类,这个类可以保存获取activity实例,记得manifest中加入android:name=".MyApp"
public class MyApp extends Application{
}
2. 在activity中保存实例
public class MyServiceActivity extends Activity {
}
3. 在service中取回实例
public class MyService extends Service {
}