NullPointerException异常的新意图 [英] NullPointerException in new Intent
本文介绍了NullPointerException异常的新意图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从服务
发送一个信息,我收到一个错误
在com.spynetstation.MediaService.notif(MediaService.java:162)错误
块引用>指向在
服务这一行
:意图notificationIntent =新意图(CTX,MediaService.class);
服务:
公共类MediaService扩展服务实现在preparedListener,OnCompletionListener { 静态的MediaPlayer媒体播放器;
静态NotificationManager纳米;
私有静态NotificationCompat.Builder mBuilder;
静态上下文CTX; 静态字符串dataPlaying = NULL;
静态字符串soursetrack = NULL;
静态的TimerTask repeatTask;
静态定时吨;
节点节点;
静态字符串文件路径;
静态文件的文件;
字符串titleNotif =站;
字符串contentNotif =运行; 公众的IBinder onBind(意向paramIntent){
返回null;
} 公共静态无效initMP(字符串URLStream)都{
尝试{
媒体播放器=新的MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(URLStream)都;
}赶上(IOException异常五){
e.printStackTrace();
}
。媒体播放器prepareAsync();
Log.d(MediaService,prepareAsync);
} 公共静态无效startMP(){
mediaPlayer.setOn preparedListener(新在preparedListener(){
@覆盖
在prepared(MediaPlayer的MP)公共无效{
mp.start();
Log.d(MediaService,开始);
MainActivity.visible();
如果(MainActivity.track){}其他{doRepeatTask();}
}
});
} 公共静态无效stopMP(){
如果(媒体播放器!= NULL){
尝试{
mediaPlayer.stop();
Log.d(MediaService,停止);
如果(MainActivity.track){}其他{STO prepeatTask();}
}赶上(例外五){
e.printStackTrace();
}
}
} 公共静态无效releaseMP(){
如果(媒体播放器!= NULL){
尝试{
mediaPlayer.release();
Log.d(MediaService,释放);
媒体播放器= NULL;
}赶上(例外五){
e.printStackTrace();
}
}
} @覆盖
公共无效onCompletion(MediaPlayer的MP){
Log.d(MediaService,onCompletion);
} @覆盖
在prepared(MediaPlayer的MP)公共无效{
Log.d(关于prepareedMediaService);
} 公共无效的onCreate(){
super.onCreate();
//尝试下面的CTX = getBaseContext();没有帮助
CTX = getApplicationContext();
this.nm =((NotificationManager)getSystemService(通知));
} 公共无效的onDestroy(){
this.nm.cancelAll();
stopForeground(真);
} 公众诠释onStartCommand(意向paramIntent,诠释paramInt1,诠释paramInt2){
尝试{
TimeUnit.SECONDS.sleep(0);
notif(titleNotif,contentNotif);
返回super.onStartCommand(paramIntent,paramInt1,paramInt2);
}赶上(InterruptedException的localInterruptedException){
为(;;){
localInterruptedException.printStackTrace();
}
}
} 公共静态无效notif(字符串titleNotif,字符串contentNotif){
//建设的通知
mBuilder =新NotificationCompat.Builder(CTX)
.setSmallIcon(R.drawable.spy)
.setContentTitle(titleNotif)
.setTicker(contentNotif); 意图notificationIntent =新意图(CTX,MediaService.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
的PendingIntent的PendingIntent = PendingIntent.getActivity(CTX,0,
notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(的PendingIntent);
通知N = mBuilder.build();
nm.notify(1,n)的;
// startForeground(12345,mBuilder.build());
} 公共静态无效doRepeatTask(){
T =新的Timer();
repeatTask =新的TimerTask(){
公共无效的run(){
新的任务()执行();
}
};
t.schedule(repeatTask,300,3000);
} 公共静态无效STO prepeatTask(){
如果(repeatTask!= NULL){
repeatTask.cancel();
Log.d(TIMER,定时器取消);
}
MainActivity.titleMusic.setText();
MainActivity.titleMusic.setVisibility(View.GONE);
} 公共静态类任务扩展的AsyncTask<太虚,太虚,太虚> {
@覆盖
保护无效doInBackground(虚空......为arg0){
尝试{
网址URL =新的URL(soursetrack);
URLConnection的连接= url.openConnection();
在的InputStream = connection.getInputStream();
文件路径= Environment.getExternalStorageDirectory()。getAbsolutePath()
+/cashe.xml
文件=新的文件(文件路径);
CreateFileFromInputStream(在,文件路径);
//使用文档生成器工厂解析
的DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
的DocumentBuilder dBuilder = NULL;
dBuilder = dbFactory.newDocumentBuilder();
文档DOC = NULL;
文档= dBuilder.parse(文件);
doc.getDocumentElement()正常化()。
//根元素是
。doc.getDocumentElement()getNodeName();
节点列表NLIST = doc.getElementsByTagName(名称); 的for(int i = 0; I< nList.getLength();我++){
element元素=(元)nList.item(I)
dataPlaying = getCharacterDataFromElement(元);
}
}赶上(MalformedURLException的E){
e.printStackTrace();
}赶上(的ParserConfigurationException E){
e.printStackTrace();
}赶上(SAXException的E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 返回null;
} @覆盖
保护无效onPostExecute(虚空结果){
如果(dataPlaying.equals(MainActivity.currentlyPlaying)){
如果(MainActivity.replay ==真){
MainActivity.replay = FALSE;
MainActivity.titleMusic.setText(+ MainActivity.currentlyPlaying);
}
}其他{
Log.d(MainActivity,更改轨道);
MainActivity.currentlyPlaying = dataPlaying;
MainActivity.titleMusic.setText(+ MainActivity.currentlyPlaying);
发送();
}
super.onPostExecute(结果);
}
} 公共静态无效的send(){
notif(MainActivity.currentlyPlaying,MainActivity.currentlyPlaying);
} 公共静态字符串getCharacterDataFromElement(元素e){
节点node = e.getFirstChild();
如果(节点的instanceof CharacterData){
CharacterData CD =(CharacterData)节点;
返回cd.getData();
}
返回;
} 公共静态无效CreateFileFromInputStream(的InputStream inStream中,字符串路径)
抛出IOException
//写的InputStream一个FileOutputStream
出的OutputStream =新的FileOutputStream(新文件(路径)); INT读= 0;
字节[]字节=新的字节[1024]; 而((读= inStream.read(字节))!= -1){
out.write(字节,0,读);
} inStream.close();
了out.flush();
out.close();
}
}LogCat中:
6月3日至12日:16:21.324:D / MediaService(3475):更改曲目
六月3日至12日:16:21.347:D / AndroidRuntime(3475):关闭VM
六月3日至12日:16:21.347:W / dalvikvm(3475):主题ID = 1:螺纹未捕获的异常(组= 0x409c01f8)退出
六月3日至12日:16:21.394:E / AndroidRuntime(3475):致命异常:主要
六月3日至12日:16:21.394:E / AndroidRuntime(3475):显示java.lang.NullPointerException
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.content.ComponentName<&初始化GT;(ComponentName.java:75)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.content.Intent<&初始化GT;(Intent.java:3122)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在com.spynetstation.MediaService.notif(MediaService.java:162)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在com.spynetstation.MediaService.send(MediaService.java:250)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在com.spynetstation.MediaService $ Task.onPostExecute(MediaService.java:241)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在com.spynetstation.MediaService $ Task.onPostExecute(MediaService.java:1)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.os.AsyncTask.finish(AsyncTask.java:602)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.os.AsyncTask.access $ 600(AsyncTask.java:156)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:615)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.os.Handler.dispatchMessage(Handler.java:99)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.os.Looper.loop(Looper.java:137)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在android.app.ActivityThread.main(ActivityThread.java:4424)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在java.lang.reflect.Method.invokeNative(本机方法)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在java.lang.reflect.Method.invoke(Method.java:511)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
六月3日至12日:16:21.394:E / AndroidRuntime(3475):在dalvik.system.NativeStart.main(本机方法)
解决方案我认为它的
背景
。而不是
CTX =此
,您可以使用
getApplicationContext()
或getBaseContext()
里面的服务来获得的上下文。尝试使用
CTX = getApplicationContext();
或
意图notificationIntent =新意图(getApplicationContext(),MainActivity.class);
参见:
从服务 机器人开始活动I'm trying to send a message from the
Service
and I receive an errorError at com.spynetstation.MediaService.notif(MediaService.java:162)
which points to this line in the
Service
:Intent notificationIntent = new Intent(ctx, MediaService.class);
Service:
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)
解决方案I think its the
context
.Instead of
ctx=this
,You can use
getApplicationContext()
orgetBaseContext()
inside your service to get the context.Try using
ctx= getApplicationContext();
OR
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
Refer: android start activity from service
这篇关于NullPointerException异常的新意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文