startforeground 服务中的空指针异常 android

null pointer exception in startforeground service android

我正在启动前台服务,但出现空指针异常。我不知道哪个是空引用。我想从服务器下载 mp3 并在通知中显示进度,就像 google play-store 对每个应用程序 downland 所做的那样。

new MyNotification(getApplicationContext() 是否为空?

07-31 14:48:39.504  21210-21210/com.sunil.divine.mybhajans E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.sunil.divine.mybhajans, PID: 21210
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
            at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
            at service.DownloadingService.startForegroundService(DownloadingService.java:47)
            at com.sunil.divine.mybhajans.List_songs.itemClick(List_songs.java:104)
            at service.SunilAdaptor$MyViewHolder.onClick(SunilAdaptor.java:75)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

请不要关闭问题。请向我解释处理此问题的正确方法。

谢谢。

以下是列表视图中每一行的 itemClick

 @Override
    public void itemClick(View view, int position) {
        Toast.makeText(this, "On ItemClick", Toast.LENGTH_LONG).show();
        Intent intent=new Intent(this, DownloadingService.class);

        switch (position){
            case 0:
                intent.putExtra("position","URL");


                //List_songs.java:104 null pointer 
                new DownloadingService().startForegroundService(position);
            break;
            case 1:
                intent.putExtra("position", "URL");


                new DownloadingService().startForegroundService(position);
                break;
        }

    }

以下是DownloadingService()class:

package service;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import java.util.concurrent.Executor;

/**
 * Created by Dell Vostro on 7/19/2015.
 */
public class DownloadingService extends Service {

    @Override
    public void onCreate() {
        Log.w("Inside","--------------Oncreate method-----------");
        Toast.makeText(getApplicationContext(),"Inside oncreate",Toast.LENGTH_LONG).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.w("Inside","--------------onStartCommand method-----------"+startId);
        String url= (String) intent.getExtras().get("position");

        String param[]={url};

        //task to download the mp3
        new DownloadFilesTask(this,startId).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,param);
        // Toast.makeText(getApplicationContext(),"Inside onStartCommand"+pos,Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void startForegroundService(int position){
        //DownloadingService.java:47 null pointer here
        startForeground(position,new MyNotification(getApplicationContext()).createNotification(position)); 
    }
}

以下是class生成通知:

package service;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.sunil.divine.mybhajans.R;

/**
 * Created by Dell Vostro on 7/30/2015.
 */
public class MyNotification {
    private int position;
    private Context context;
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;

    public MyNotification() {

    }

    public MyNotification(Context context) {
        this.context=context;
    }

    public android.app.Notification createNotification(int position) {

        mNotifyManager =
                (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setContentTitle("Song Download")
                .setContentText("Download in progress")
                .setSmallIcon(R.mipmap.ic_launcher);
        // Sets the progress indicator to a max value, the
        // current completion percentage, and "determinate"
        // state
        mBuilder.setProgress(100, new DownloadFilesTask().getCalculatedProgress(), false);
        // Displays the progress bar for the first time.
        mNotifyManager.notify(position, mBuilder.build());
        return mBuilder.build();
    }
    // Update the progress bar
    public void updateNotification(int calculatedProgress,int startId){
        mBuilder.setProgress(100, calculatedProgress, false);

        mNotifyManager.notify(startId, mBuilder.build());
    }
}

好吧,你的问题是这不是你在前台启动服务的方式。您应该阅读 Android Services、它们的生命周期以及如何启动服务。您的代码包含几个基本错误。

查看此示例,了解如何启动 foreground service

就您的代码的具体问题而言,最简单的解释是,您应该启动一个启动服务的意图,然后在服务中(当它是 运行 并且具有正确的上下文时),调用开始前景。相反,您创建一个对象并从您的应用程序中调用 startforeground。