Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6180199
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T00:48:17+00:00 2026-05-24T00:48:17+00:00

I have written an android service, that I need to run in the background

  • 0

I have written an android service, that I need to run in the background and be able to communicate with the rest of the application. The code is as given below. The problem is that, when the service is invoked, the application force closes. And apparently it isnt reaching the service itself as none of the log commands I have written in onCreate, onStart etc is being printed

package com.org.EasyUpload;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Application;
import android.app.DownloadManager;
import android.app.NotificationManager;
import android.app.Service;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class DownloadSnifferActivity extends Service {

    public static DownloadManager MAIN_ACTIVITY;
    private Timer timer = new Timer();
    private static long SNIFF_INTERVAL = 1000;
    private static long DELAY_INTERVAL = 1000;

    SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
    DownloadManager downloadManager;

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("service","Control is in the onStartCommand");
//      /_startService();
        return START_STICKY;
    }


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

    public void onCreate () {
        super.onCreate();
        Log.d("onCreate", "Inside onCreate");
        _startService();
    }

    public void onDestroy (){
        super.onDestroy();
        _shutdownService();
    }

    public void onDownloadStart(String url, String userAgent, String contentDisposition, 
            String mimeType, long size) {

        Log.d("URL",url);
    }

    public void _startService(){
        Log.d("DownloadSniffer", "Inside the thread");
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    readDownloadManager();
                    Log.d("Thread", "The download sniffer service is running");
                    Thread.sleep(SNIFF_INTERVAL);
                }catch(InterruptedException ex) {
                    Log.d("Exception",ex.toString());
                    ex.printStackTrace();
                }
            }
        }, DELAY_INTERVAL, SNIFF_INTERVAL);
    }

    public void _shutdownService() {

    }


    public void readDownloadManager() {
        DownloadManager.Query query = null;
        DownloadManager downloadManager = null;
        Cursor c = null;
        int statusColumnIndex = 0 ;
        int urlColumnIndex = 0;
        long downloadProcessIdColumnNo ;
        try {
            query = new DownloadManager.Query();
            downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);

            //Just for testing I initiated my own download from this url. When an http
            // reuest for this url is made, since download is taking place, it gets saved in
            // the download manager.
            Request request = new Request(Uri.parse("http://ocw.mit.edu/courses" +
                    "/aeronautics-and-astronautics/16-100-aerodynamics-fall-2005" +
                    "/lecture-notes/16100lectre1_kvm.pdf"));
            if(downloadManager!=null){
                downloadManager.enqueue(request);
            } else {
                return;
            }
            if(query!=null) {
                query.setFilterByStatus(DownloadManager.STATUS_PENDING);
            } else {
                return;
            }
            c = downloadManager.query(query);
            Log.d("Inside", "Atleast Inside");
            Log.d("Query",c.toString());
            if(true){
                statusColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                urlColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_URI);
                downloadProcessIdColumnNo = c.getColumnIndex(DownloadManager.COLUMN_ID);
                Log.d("Column Count", ((Integer)c.getCount()).toString());
                c.moveToFirst();
                if(c.getCount() > 0){
                    String url="";
                    if(!c.isAfterLast()){
                        url = c.getString(urlColumnIndex);
                        downloadManager.remove(downloadProcessIdColumnNo);
                        Log.d("Count after remove", ((Integer)c.getCount()).toString());
                        c.moveToNext();
                    }
                    Log.d("After", "Stopped Working");
                    Log.d("url:", url);
                    //Here I am sending the url to another activity, where I can work with it.
                    Intent intent = new Intent(DownloadSnifferActivity.this, EasyUploadActivity.class);
                    Bundle b = new Bundle();
                    b.putString("url", url);
                    intent.putExtras(b);
                    startActivity(intent);
                } else {
                    return;
                }
            }

        } catch (NullPointerException ex) {
            ex.printStackTrace();
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
        }
    }
}

I have also made the following entry in AndroidManifest.xml :

<service android:enabled="true" android:name=".DownloadSnifferActivity">
        </service>

And this is how I make the call to the service to start it:

startService(new Intent(EasyUploadMainMenu.this, DownloadSnifferActivity.class)); 

Exception logged in LogCat:

07-28 05:25:06.447: ERROR/AndroidRuntime(348): FATAL EXCEPTION: main
07-28 05:25:06.447: ERROR/AndroidRuntime(348): java.lang.RuntimeException: Unable to instantiate service com.org.EasyUpload.DownloadSnifferActivity: java.lang.NullPointerException
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:1904)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.app.ActivityThread.access$2500(ActivityThread.java:117)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:982)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.os.Looper.loop(Looper.java:123)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.app.ActivityThread.main(ActivityThread.java:3647)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at java.lang.reflect.Method.invokeNative(Native Method)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at java.lang.reflect.Method.invoke(Method.java:507)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at dalvik.system.NativeStart.main(Native Method)
07-28 05:25:06.447: ERROR/AndroidRuntime(348): Caused by: java.lang.NullPointerException
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:353)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:348)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at com.org.EasyUpload.DownloadSnifferActivity.<init>(DownloadSnifferActivity.java:33)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at java.lang.Class.newInstanceImpl(Native Method)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at java.lang.Class.newInstance(Class.java:1409)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:1901)
07-28 05:25:06.447: ERROR/AndroidRuntime(348):     ... 10 more
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T00:48:17+00:00Added an answer on May 24, 2026 at 12:48 am

    What does the keyword this means in this line?

    SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
    

    The context is not correct. You can’t write this line before the service is initialized. Just declare SharedPreferences preferenceManager; in the class and preferenceManager =
    PreferenceManager.getDefaultSharedPreferences(this);
    in onCreate().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written an application for Android. the main part being that it communicates
I have written an Android application that uses SQLite database which is saved in
I have written an Android application that I am about to release, but I
I have written a simple Android application that uses a sqlite database which is
I'm just starting with android development and have written an application to show details
I have written an android app that saves (potentially) large files to the SD
I have an app written for Android 2.2 (API 8) that depends on some
I have web services written using java which interacts with the android application only
I have written REST web service in netbean IDE using jersey framework and java.
I am new to web services. I have written a rest web service which

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.