startforeground服务android中的空指针异常

时间:2015-07-31 19:09:25

标签: java android android-asynctask android-service foreground-service

我正在启动前台服务,我得到一个空指针异常。我没有得到哪个是空引用。我想从服务器下载这个mp3,并显示谷歌游戏商店为每个应用程序进行的通知进度。

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

1 个答案:

答案 0 :(得分:0)

Well, your issue is that's not how you start a service in the foreground. You should read about Android Services, their lifecycle, and how to start a service. Your code contains several fundamental mistakes.

Take a look at this example for how to launch a foreground service

In terms of what's specifically wrong with your code, the simplest explanation is that, you should start an intent that starts the service then within the service (while it is running and has correct context), call startforeground. Instead, you create an object and call startforeground from within your application.