android service 怎么结束activity
发布网友
发布时间:2022-04-30 18:15
我来回答
共2个回答
热心网友
时间:2022-06-28 23:40
方法一:
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.startService(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;
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
……
//启动mService
mService.startservice(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 {
/** Called when the activity is first created. */
@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();
……
}
}
热心网友
时间:2022-06-28 23:41
serview是后台运行的,如果要通知activity结束的话,可以使用回调接口或者广播来实现。