我的Android App即使在关闭后也会使用CPU

时间:2013-07-13 12:19:18

标签: android

我的应用程序耗尽电池。我已经使用了将请求发送到url的服务。从我的类调用服务,扩展了Application.Below是我的代码。

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,请建议如何停止服务..提前谢谢

2 个答案:

答案 0 :(得分:2)

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

  

此方法适用于模拟过程环境。永远不会   在生产Android设备上调用,删除进程   简单地杀死他们;没有用户代码(包括此回调)   执行时执行。

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

如果您想知道该应用何时关闭&#34;,您需要跟踪活动的状态。例如,您可以使用全局计数器来计算活动活动的数量。对于每个onCreate,你增加它的价值。对于每个onDestroy,您可以减少其值。当它达到0时,表示当前没有活动。

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

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

答案 1 :(得分:1)

您需要使用IntentService代替Service。这样,一旦完成任务,服务就会自行关闭。