我在主要活動暫停時運行此任務,並在主要活動恢復時停止任務。 但不能在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;
}
}
你在哪裏調用createNotification()?爲了獲得最好的幫助,請提供擴展AsyncTask的全部類。 – Zerkz
編輯第一條消息 – omerfirmak
'alarmToggle'做什麼?它是「布爾」嗎? –