【问题标题】:NullPointerException in new Intent新意图中的 NullPointerException
【发布时间】:2014-03-12 05:07:44
【问题描述】:

我正在尝试从Service 发送消息,但收到错误消息

com.spynetstation.MediaService.notif(MediaService.java:162) 出错

Service中指向这一行:

Intent notificationIntent = new Intent(ctx, MediaService.class);

服务:

public class MediaService extends Service implements OnPreparedListener,OnCompletionListener{

    static MediaPlayer mediaPlayer;
    static NotificationManager nm;
    private static NotificationCompat.Builder mBuilder;
    static Context ctx;

    static String dataPlaying = null;
    static String soursetrack = null;
    static TimerTask repeatTask;
    static Timer t;
    Node node;
    static String filePath;
    static File file;
    String titleNotif = "Station";
    String contentNotif = "Running";

    public IBinder onBind(Intent paramIntent)  {
        return null;
    }

    public static void initMP(String urlStream){
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(urlStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        Log.d("MediaService", "prepareAsync");
    }

    public static void startMP(){
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {  
            @Override  
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                Log.d("MediaService", "start");
                MainActivity.visible();
                if (MainActivity.track) {} else {doRepeatTask();}
            }
        });   
    }

    public static void stopMP() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop(); 
                Log.d("MediaService", "stop");
                if (MainActivity.track) {} else {stopRepeatTask();}
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void releaseMP() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release();
                Log.d("MediaService", "release"); 
                mediaPlayer = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.d("MediaService", "onCompletion"); 
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.d("MediaService", "onPrepareed");
    }

    public void onCreate()  {
        super.onCreate();
        // tried the following ctx=getBaseContext(); did not help
        ctx = getApplicationContext();
        this.nm = ((NotificationManager)getSystemService("notification"));
    }

    public void onDestroy()  {
        this.nm.cancelAll();
        stopForeground(true);
    }

    public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2)  {
        try {
            TimeUnit.SECONDS.sleep(0);
            notif(titleNotif, contentNotif);
            return super.onStartCommand(paramIntent, paramInt1, paramInt2);
        } catch (InterruptedException localInterruptedException) {
            for (;;) {
                localInterruptedException.printStackTrace();
            }
        }
    }

    public static void notif(String titleNotif, String contentNotif){
        //building the notification
        mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.spy)
            .setContentTitle(titleNotif)
            .setTicker(contentNotif);

        Intent notificationIntent = new Intent(ctx, MediaService.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, 
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        Notification n = mBuilder.build();
        nm.notify(1, n);
        // startForeground(12345, mBuilder.build());
    }

    public static void doRepeatTask(){
        t = new Timer();
        repeatTask = new TimerTask() {
            public void run() {
                new Task().execute();
            }
        };
        t.schedule(repeatTask, 300, 3000); 
    }

    public static void stopRepeatTask(){
        if(repeatTask!=null){
            repeatTask.cancel();
            Log.d("TIMER", "timer canceled");
        }
        MainActivity.titleMusic.setText("");
        MainActivity.titleMusic.setVisibility(View.GONE);
    }

    public static class Task extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                URL url = new URL(soursetrack);
                URLConnection connection = url.openConnection();
                InputStream in = connection.getInputStream();
                filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/cashe.xml";
                file = new File (filePath);
                CreateFileFromInputStream(in,  filePath) ;
                // Parse it with document builder factory
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = null;
                dBuilder = dbFactory.newDocumentBuilder();
                Document doc = null;
                doc = dBuilder.parse(file);
                doc.getDocumentElement().normalize();
                // The root element is 
                doc.getDocumentElement().getNodeName();
                NodeList nList = doc.getElementsByTagName("Name");

                for ( int i = 0 ; i < nList.getLength() ; i++ ) {
                    Element element = (Element) nList.item(i) ;
                    dataPlaying = getCharacterDataFromElement(element);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace(); 
            } catch (ParserConfigurationException e) {
                e.printStackTrace(); 
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace(); 
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (dataPlaying.equals(MainActivity.currentlyPlaying)){
                if (MainActivity.replay == true){
                    MainActivity.replay = false;
                    MainActivity.titleMusic.setText("" + MainActivity.currentlyPlaying); 
                }
            } else {
                Log.d("MainActivity","Change track");
                MainActivity.currentlyPlaying = dataPlaying;
                MainActivity.titleMusic.setText("" + MainActivity.currentlyPlaying);
                send();
            }
            super.onPostExecute(result);  
        }
    }

    public static void send(){
        notif(MainActivity.currentlyPlaying,MainActivity.currentlyPlaying);
    }

    public static String getCharacterDataFromElement(Element e) {
        Node node = e.getFirstChild();
        if (node instanceof CharacterData) {
            CharacterData cd = (CharacterData) node;
            return cd.getData();
        }
        return "";
    }

    public static void CreateFileFromInputStream(InputStream inStream, String path)
            throws IOException {
        // write the inputStream to a FileOutputStream
        OutputStream out = new FileOutputStream(new File(path));

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        inStream.close();
        out.flush();
        out.close();
    }
}

LogCat:

03-12 06:16:21.324: D/MediaService(3475): Change track
03-12 06:16:21.347: D/AndroidRuntime(3475): Shutting down VM
03-12 06:16:21.347: W/dalvikvm(3475): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
03-12 06:16:21.394: E/AndroidRuntime(3475): FATAL EXCEPTION: main
03-12 06:16:21.394: E/AndroidRuntime(3475): java.lang.NullPointerException
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.content.ComponentName.<init>(ComponentName.java:75)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.content.Intent.<init>(Intent.java:3122)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at com.spynetstation.MediaService.notif(MediaService.java:162)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at com.spynetstation.MediaService.send(MediaService.java:250)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at com.spynetstation.MediaService$Task.onPostExecute(MediaService.java:241)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at com.spynetstation.MediaService$Task.onPostExecute(MediaService.java:1)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.os.AsyncTask.finish(AsyncTask.java:602)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.os.Looper.loop(Looper.java:137)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at android.app.ActivityThread.main(ActivityThread.java:4424)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at java.lang.reflect.Method.invokeNative(Native Method)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at java.lang.reflect.Method.invoke(Method.java:511)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-12 06:16:21.394: E/AndroidRuntime(3475):     at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

  • 由于 currentPlaying 中没有值。它为空。使用日志检查一次。
  • currentlyPlaying not null 未发送通知标题曲目显示正常
  • 还可以创建通知管理器,例如:NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  • 在onCreate()方法中,尝试使用this.ctx = getApplicationContext();
  • 谢谢,但没有帮助:(

标签: android android-intent nullpointerexception android-service android-notifications


【解决方案1】:

我认为是context

而不是ctx=this

您可以在服务中使用getApplicationContext()getBaseContext() 来获取上下文。

尝试使用

ctx= getApplicationContext();

Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

参考: android start activity from service

【讨论】:

  • 你尝试过干净的构建,你确定它是同样的错误吗,在那一行看起来并不多
  • 我删除了处理当前跟踪和调度 mainactivity 通知的代码,并将他置于 mediaservice 但同样的错误和更严格的线路
【解决方案2】:

替换

 Intent notificationIntent = new Intent(ctx, MainActivity.class);

 Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);

或者

 Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

【讨论】:

  • 如果我使用 ctx=getBaseContext();该错误与 Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class); 相同是改变只写“不能对ContextWrapper类型的非静态方法getBaseContext()进行静态引用”
  • 尝试使用Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
【解决方案3】:

因为,Intent.FLAG_ACTIVITY_SINGLE_TOP 标志不支持这个。
因此,您可以尝试使用 getApplicationContext() 或 getBaseContext() 代替 ctx。
你可以读这个。它可以帮助你。 android start activity from service

【讨论】:

    【解决方案4】:

    您在 ctx 中传递了一个空上下文变量。此外,您的架构很奇怪——notif 不应该是服务上的静态成员。它应该是一个非静态的普通成员函数。您永远不应该在任何地方对 Context 进行静态引用 - 会导致泄漏。而且它不需要,因为服务是一个上下文,如果 notif 不是静态的,它应该能够传递它。每当您发现自己将多个静态变量放入这样的类中时,这表明您设计错误。

    【讨论】:

      【解决方案5】:

      用途:-

      Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
      

      【讨论】:

      • 如果我使用 ctx=getApplicationContext();该错误与 Intent notificationIntent = new Intent(getApplicationContext, MainActivity.class); 相同是改变只写“不能对ContextWrapper类型的非静态方法getApplicationContext()进行静态引用”
      【解决方案6】:

      您在 ctx 中传递了一个空上下文变量。 好吧,我有解决方案,而且效果很好,您必须在主类中创建一个静态上下文,然后使用该上下文

      public class LauncherActivityname extends ..... {
      
      public static Context context;
      .
      .
      .
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          context=this
      }
      }
      

      使用这个上下文 insted of yout ctx 并像使用它一样

      Intent notificationIntent = new Intent(LauncherActivityname.context, MainActivity.class);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-20
        • 1970-01-01
        相关资源
        最近更新 更多