java - 调用服务时 Android 应用程序强制关闭

标签 java android android-emulator android-manifest

我已经编写了一个 android 服务,我需要在后台运行并能够与应用程序的其余部分进行通信。代码如下。问题是,当调用服务时,应用程序强制关闭。显然它没有到达服务本身,因为没有打印我在 onCreate、onStart 等中编写的日志命令

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

我还在 AndroidManifest.xml 中做了以下条目:

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

这就是我调用服务以启动它的方式:

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

异常记录在 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

最佳答案

关键字 this 在这一行中是什么意思?

SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);

上下文不正确。你不能在服务初始化之前写这行。只需在类中声明 SharedPreferences preferenceManager;preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);onCreate() 中。

关于java - 调用服务时 Android 应用程序强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6854369/

相关文章:

java - 如何将Java代码写入Spring配置文件

android - 如何使用 Tabs 和 Pager 示例替换 ActionBarSherlock 中的选项卡使用的 fragment ?

android - 模拟器 JBMR1 中的外部显示功能测试

java - 为什么 Eclipse 找不到我的主类

java - 如何在嵌入的网络浏览器中从 URL 播放 .wav 文件 - Java

java - 开发 Eclipse 插件期间的运行时问题

android - ViewPager 和更新 Fragments

android - 如何删除项目名称并替换为android导航栏上的图标?

android - 如何获取 Android AVD 中可用的示例演示应用程序的源代码

java - 使用不同计算机上的模拟器将客户端连接到服务器