如何在 Android 中自动停止服务

How to stop service automatically in Android

我在 Android 中的单个 Activity 中使用了两项服务,并在我的 activity 启动时启动这些服务。我正在尝试在两种服务的 onStartCommand() 中下载一些图像。但是现在我想自动停止服务或在 onStartCommand() 完成他的 work.How 后自行停止服务,我是否在完成 onStartCommand() 后自行停止服务。谢谢 !!

此服务在 Activity

的 onCreate() 中启动
Intent intent_Service = new Intent(CustomActionActivity.this , DownLodProfileSrvice.class);
        startService(intent_Service);

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

这是我的服务代码

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();
            }

}

实际上您不需要下载文件的服务! 服务是一种执行长 运行 任务的工具,这不是你的情况。下载文件的最佳做法是只使用 AsyncTask.

LoadProfilePics 移动到您的 activity 并只执行一次。 您还可以检查 onPostExecution.

中 AsyncTask 的 doInBackground 结果

有关 AsyncTask

的更多信息,请参阅 this link

服务完成后可以调用 stopSelf()。如果您使用 IntentService,这将自动发生。