0

我的应用程序耗尽了电池。我使用了将请求发送到 url 的服务。该服务是从我的扩展应用程序的类中调用的。下面是我的代码。

public class GApplication extends Application {
private static final String TAG ="GApplication";
private HttpClient httpClient;
private DatabaseHelper databaseHelper;

@Override
public void onCreate(){
    super.onCreate();   
    startService(new Intent(this, GService.class));
    httpClient = createHttpClient();
    databaseHelper = new DatabaseHelper(this);
}

@Override
public void onLowMemory(){
    super.onLowMemory();
    shutdownHttpClient();
}

@Override
public void onTerminate(){
    super.onTerminate();
    stopService(new Intent(this, GService.class));
    shutdownHttpClient();
    databaseHelper.close();
}

private void shutdownHttpClient(){
    if(httpClient != null && httpClient.getConnectionManager() != null){
        httpClient.getConnectionManager().shutdown();
    }
}

public DatabaseHelper getDatabaseHelper(){
    if(databaseHelper == null){
        databaseHelper = new DatabaseHelper(this);
    }
    return databaseHelper;
}

public HttpClient getHttpClient(){
    return httpClient;
}

public HttpClient createHttpClient(){
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", PlainSocketFactory.getSocketFactory(), 443));
    return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
}

public boolean isOnline(){
    boolean isConnected = false;
    try{
        ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        isConnected = (info != null && info.isAvailable() && info.isConnected());
    }
    catch(Exception e){
        isConnected = false;
        if(e.getMessage() != null) Log.e(TAG, e.getMessage());
    }
    return isConnected;
}

}

我的 Gservice 课程

public class GService extends Service {
private static final String TAG = "Gservice";



public IBinder onBind(Intent intent) {
    return null;
}   


public void onCreate(){
    super.onCreate();
    Log.i(TAG, "starting GService");

    if(isOnline()){
        URI uri = URI.create("http://myserver/Android/UploadImage/newAlert.php");
        new UpdateCheckAsyncTask(getHttpClient()).execute(uri); 
    }

}



boolean isOnline(){
    return ((GApplication)getApplication()).isOnline();
}

HttpClient getHttpClient(){
    return  ((GApplication)getApplication()).getHttpClient();
}

DatabaseHelper getDatabaseHelper(){
    return  ((GApplication)getApplication()).getDatabaseHelper();
}



class UpdateCheckAsyncTask extends WebAsyncTaskBase{
    public UpdateCheckAsyncTask(HttpClient httpClient) {
        super(httpClient);
    }


    protected String doInBackground(URI... params) {
        return getHttpContent(params[0]);
    }


    protected void onProgressUpdate(Integer... progress){

    }


    protected void onPostExecute(String result){
        if(result == null){
            Log.i(TAG, "Call returned null");
            return;
        }
        try {
            Log.i(TAG, "Processsing request");
            JSONObject json = new JSONObject(result);
            new BlogDbAsyncTask(getDatabaseHelper()).execute(json);
        } catch (JSONException e) {
            if(e.getMessage() != null) Log.e(TAG, e.getMessage());
        }
    }

    class BlogDbAsyncTask extends DbAsyncTaskBase<JSONObject, Boolean, BlogInfo>{

        public BlogDbAsyncTask(DatabaseHelper database) {
            super(database);
        }

        @Override
        protected BlogInfo doInBackground(JSONObject... json) {
            BlogInfo blogInfo = new BlogInfo();
            BlogDAO dao = new BlogDAO(GService.this, getDatabaseHelper());
            try {
                Log.i(TAG, "Adding new blog entry");
                Blog blog = dao.Select(json[0].getInt("FeedId"));
                if(blog.UID == null){
                    blog.UID = json[0].getInt("FeedId");
                    blog.Text = json[0].getString("Text");
                    blog.Title = json[0].getString("Header");
                    blog.PostedOn = json[0].getString("DisplayDate");
                    blog.PostedBy = "Gservice";
                    dao.Insert(blog);

                    blogInfo.Blog = blog;
                    blogInfo.IsNew = true;
                }
            } catch (JSONException e) {
                if(e.getMessage() != null) Log.e(TAG, e.getMessage());
            }
            return blogInfo;
        }


        protected void onPostExecute(BlogInfo result){


        }

    }

    class BlogInfo{
        public Blog Blog;
        public boolean IsNew;
    }
}

可能永远不会在 GApplication 类中调用 Onterminate 方法,这会使服务连续运行。请建议是否可以使用此代码发现任何问题。此外,如果从未在设备中调用 onterminate,请建议如何停止服务..提前致谢。

4

2 回答 2

2

onTerminate不应该在真实设备上调用:

此方法用于模拟过程环境。它永远不会在生产 Android 设备上调用,在这些设备上,只需杀死进程即可删除它们;这样做时不会执行任何用户代码(包括此回调)。

您应该考虑改用服务,并根据您的需要使用适当的服务。

如果您想知道应用程序何时“关闭”,您需要跟踪活动的状态。例如,您可以有一个全局计数器来计算活动活动的数量。对于每个 onCreate,您都会增加它的值。对于每个 onDestroy,您都会减少它的值。当它达到 0 时,表示当前没有活动处于活动状态。

但是,应该警告您它不是很准确,因为当配置发生更改时,活动将被销毁并重新创建,因此您也需要处理它。

正如我已经提到的,您应该考虑改用服务。可能会在您需要的每个活动上绑定到它,并在活动被销毁时取消绑定。甚至可以让它在前台运行并按需关闭它......一切都取决于您的要求。

于 2013-07-13T14:20:16.860 回答
1

您需要使用 anIntentService而不是Service. 这样,一旦完成任务,服务就会自行关闭。

于 2013-07-13T12:32:18.077 回答