简体   繁体   English

如何在Android中自动停止服务

[英]How to stop service automatically in Android

i have used two services in single Activity in Android and start the services when my activity is start. 我在Android的单个Activity中使用了两项服务,并在我的Activity开始时启动了服务。 I'm trying to downloading some images in onStartCommand() in Both services. 我正在尝试在两种服务的onStartCommand()中下载一些图像。 But right now i want to stop the services automatically or stop it self after onStartCommand() finished his work.How do I stop service it self after finishing the onStartCommand().Thanks !! 但是现在我想自动停止服务或在onStartCommand()完成工作后自行停止服务。如何在完成onStartCommand()之后停止自我服务。谢谢!

This start service in onCreate() in Activity 活动中onCreate()中的启动服务

Intent intent_Service = new Intent(CustomActionActivity.this , DownLodProfileSrvice.class);
        startService(intent_Service);

        Intent intent = new Intent(CustomActionActivity.this, MyService.class);
        startService(intent);

Here is my service code 这是我的服务代码

public class DownLodProfileSrvice extends Service
        {
protected SQLiteDatabase db;
public Runnable mRunnable=null;
        MyDbHelper myDBHelper;
        String namespace="http://103.24.4.60/xxxxx/xxxxx.svc";
        File newFolder;

        public ImageLoader imageLoader;
        DisplayImageOptions options;
        String str_Authentication_Token,result;
            public DownLodProfileSrvice(){

        }

        @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();
        Log.e("TAG","ScreenListenerService---OnCreate ");

        myDBHelper=new MyDbHelper(this);
        myDBHelper.onOpen(db);
       }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        final Handler mHandler=new Handler();
        mRunnable=new Runnable(){
    @Override
    public void run()
        {
        new LoadProfilePic().execute();

        mHandler.postDelayed(mRunnable,10*1000);
        }
        };
        mHandler.postDelayed(mRunnable, 10 *1000);

        return super.onStartCommand(intent,flags,startId);
        }

    private class LoadProfilePic extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... arg0) {
        LoadProfilePics();
        return null;
    }

}

            public void LoadProfilePics() {
                db = myDBHelper.getWritableDatabase();

                Cursor cursor = db.rawQuery("select * from ALL_Post ", null);
                if (cursor.moveToFirst()) {
                do {
                String strProfile_Pics = cursor.getString(cursor.getColumnIndex("ProfilePICURL"));
                String strDownLoadStatus = cursor.getString(cursor.getColumnIndex("DownLoad_Status"));
                if(strDownLoadStatus.equals("0"))
                {
                    String URL_downLoadProfilePic = namespace + "/DownloadFile/FilePathMobile/PROFILEPICPATH/FileName/" + strProfile_Pics;
                    newFolder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "classNKK_ProfilePic");
                    download_PngFileImgLoader(URL_downLoadProfilePic, newFolder, strProfile_Pics);
                    db.execSQL("update ALL_Post set DownLoad_Status='1' where ProfilePICURL ='" + strProfile_Pics + "'");
                    Log.e("URL_downLoadProfilePic ", " ==========>" + URL_downLoadProfilePic);

                }

            } while (cursor.moveToNext());
        }
        cursor.close();
            }

}

The service can call stopSelf() when it is done. 服务完成后可以调用stopSelf()。 If you use IntentService, this will happen automatically. 如果您使用IntentService,这将自动发生。

Actually you don't need a service for downloading a file! 实际上,您不需要下载文件的服务! Services are a tool for performing long running tasks which is not your case. 服务是执行长期运行任务的工具,而事实并非如此。 The best practice for downloading a file is to just use an AsyncTask . 下载文件的最佳做法是仅使用AsyncTask

Move LoadProfilePics to your activity and execute it just once. LoadProfilePics移至您的活动并仅执行一次。 Also you can check the result of doInBackground of the AsyncTask in onPostExecution . 您也可以在doInBackground中检查AsyncTask的onPostExecution

See this link for more information on AsyncTask 请参阅链接的详细信息AsyncTask

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM