从asynctask创建通知

时间:2014-01-14 16:56:43

标签: android

当我的mainactivity暂停时我运行此任务,并在mainactivity恢复时停止任务。 但是无法在asynctask中获得通知。 我在通知构建器的build()方法中获得了nullpointerexception。

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 个答案:

答案 0 :(得分:1)

我很确定这是因为mContext未分配为null以外的其他内容。当您声明它时,请尝试将其设置为YourActivity.this