-2

我正在启动一个前台服务,我得到一个空指针异常。我没有得到哪个是空引用。我想从服务器下载 mp3 并在通知中显示进度,就像 google play-store 为每个应用程序所做的那样。

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)

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

谢谢。

以下是 Listview 中每一行的 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()课程:

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

以下是生成通知的类:

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

1 回答 1

0

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

看一下这个例子,了解如何启动前台服务

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

于 2015-07-31T19:42:34.273 回答