Android:在后台运行应用程序
在我的应用程序中,当我退出应用程序时,它不会在后台运行并完全关闭,但我希望应用程序在后台继续运行,我如何才能做到这一点 这是我的代码:Android:在后台运行应用程序,android,Android,在我的应用程序中,当我退出应用程序时,它不会在后台运行并完全关闭,但我希望应用程序在后台继续运行,我如何才能做到这一点 这是我的代码: @Override public void onBackPressed() { new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit") .setMessage("Are you su
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}).setNegativeButton("No", null).show();
}
使用服务在后台运行应用程序: 服务是一种应用程序组件,它可以在后台执行长时间运行的操作,并且不提供用户权限 接口
尝试下面的示例代码
public class BackHelper extends Service {
private static final String TAG = "me.trial";
@Override
public void onCreate()
{
Log.i(TAG, "Service onCreate" );
super .onCreate();
new sock().call();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.i(TAG, "Service onDestroy" );
super .onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i(TAG, "Service onstart" );
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Service onBind" );
return null ;
}
}
像这样从您的活动中调用服务
Intent intent = new Intent(YourActivity.this, BackHelper.class);
startService(intent);
还加
在舱单内
tag您能帮我使用什么吗?请了解服务并尝试实施它。堆栈溢出不是帮助代码的位置。试着实现它,如果你面临任何问题,然后问问题。任何人都可以帮你解决这个问题。你说的不正确是什么意思?当我在intelij中添加这段代码时,有一些错误,例如onCreate()出错,或者你应该导入它的标题,使用快捷方式cntrl+shift+o