2014-01-14 95 views
0

我在主要活動暫停時運行此任務,並在主要活動恢復時停止任務。 但不能在asynctask上得到通知工作。 我在通知構建器的build()方法中獲得了nullpointerexception。從async服務器創建通知

public class Alarm extends AsyncTask<String, Void, String>{ 
    private Context mContext; 
    private int NOTIFICATION_ID = 1; 
    private Notification noti; 
    private NotificationManager nm; 
    PendingIntent contentIntent; 
    protected void onPreExecute(String... params) { 
     Intent notificationIntent = new Intent(mContext.getApplicationContext(), MainActivity.class); 
     contentIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 
       0, notificationIntent, 
       PendingIntent.FLAG_CANCEL_CURRENT); 
    } 


    private void createNotification() { 
     noti = new NotificationCompat.Builder(mContext) 
     .setContentIntent(contentIntent) 
     .setContentTitle("New mail from ") 
     .setContentText("deneme") 
     .setSmallIcon(R.drawable.ic_launcher) 
     .build(); 
      nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); 
      nm.notify(NOTIFICATION_ID, noti); 
     } 


    protected String doInBackground(String... params) {  
    if(MainActivity.alarmToggle.isChecked()){ 
     while(true){ 
     try{  
      Thread.sleep(1000); 
      StringBuilder builder = new StringBuilder(); 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet requestedUrl = new HttpGet("http://www.btcturk.com/api/ticker"); 
      HttpResponse response; 
      response = client.execute(requestedUrl);   
      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       InputStream inputStream = entity.getContent(); 
       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
       for (String line = null; (line = bufferedReader.readLine()) != null;) { 
        builder.append(line).append("\n"); 
       } 
      } 
      Map<String, Double> map = new Gson().fromJson(builder.toString(), new TypeToken<HashMap<String, Double>>() {}.getType()); 
      if(map.get("last") <= MainActivity.dusukLimitVal && MainActivity.dusukLimitVal != 0){   
       createNotification(); 
      } 

      if(map.get("last") >= MainActivity.yuksekLimitVal && MainActivity.yuksekLimitVal != 0){   
       createNotification(); 
      }  
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
      if (isCancelled()) break; 
     } 
    } 
     return null; 
    } 
} 
+1

你在哪裏調用createNotification()?爲了獲得最好的幫助,請提供擴展AsyncTask的全部類。 – Zerkz

+0

編輯第一條消息 – omerfirmak

+0

'alarmToggle'做什麼?它是「布爾」嗎? –

回答

1

我很確定這是因爲mContext未被指定爲非空值。當你聲明它時試着將它設置爲等於YourActivity.this

+0

你的意思是像MainActivity.this?我想我有點失落:) – omerfirmak

+0

是的,就像那樣。 –

+0

謝謝。它現在就像一個魅力:) – omerfirmak