【问题标题】:Android show notification in the service methodAndroid 在服务方法中显示通知
【发布时间】:2015-03-29 07:45:58
【问题描述】:

感谢您阅读我的问题。
我编写了简单的应用程序来向运行后台的服务显示通知:
我将其写入服务类以显示简单的通知:

NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(getBaseContext())
                        .setSmallIcon(R.drawable.maleki) // notification icon
                        .setContentTitle("آذر گشت") // title for notification
                        .setContentText("شما"+" "+jsonArray.length()+" "+"خبر جدید دارید") // message for notification
                        .setAutoCancel(true); // clear notification after click


但没有显示通知,会发生什么?谢谢。

我的完整服务类代码是:

public class newsservice extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // your code
        new HttpAsyncTask().execute("http://tour.maxitem.org/newslenght.aspx");
        //this.stopSelf();

        return Service.START_FLAG_REDELIVERY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //************************************************************
    //***************************************AsyncTask

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            TourMyCountry country=new TourMyCountry();
            country.id="jamalnews";//.setName(etName.getText().toString());
            return POST(urls[0],country);
        }
        // onPostExecute displays the results of the AsyncTask.
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {


            try {
                JSONArray jsonArray=new JSONArray(result);
                /*for(int i=0;i<jsonArray.length();i++)
                {
                    JSONObject JsonObj=jsonArray.getJSONObject(i);
                    String countryname=JsonObj.getString("countryname");

                }*/

                /*NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(getBaseContext())
                        .setSmallIcon(R.drawable.maleki) // notification icon
                        .setContentTitle("آذر گشت") // title for notification
                        .setContentText("شما"+" "+jsonArray.length()+" "+"خبر جدید دارید") // message for notification
                        .setAutoCancel(true); // clear notification after click*/

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }//END OF ASYNCTASK

    //**************************************POST LEVEL
    public static String POST(String url, TourMyCountry myCountry){
        InputStream inputStream = null;
        String result = "";
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("id", myCountry.id);
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
            Log.d("behzad in the service:",result);

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }//END OF POST BACK TO RETURN

    //************************************************convertInputStreamToString
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
    //***************************************************************


    public class TourMyCountry{
        String id;
    }

}

【问题讨论】:

  • 您提供的来源不够。分享更多,例如您必须实际显示通知的呼叫。包含更多代码,或者我建议在没有足够信息的情况下关闭它)。
  • @Booger 我更新问题
  • 你还没有调用 notify() 方法,它在哪里?
  • @DavidJhons 我怎么称呼它?
  • 为什么你的服务类中有一个 AsyncTask?!这已经脱离了 UI 线程,所以你不需要也不想要这个。

标签: android notifications


【解决方案1】:

试试这个,

NotificationManager mNotifyMgr = (NotificationManager)   getSystemService(Context.NOTIFICATION_SERVICE);

// your code for notification builder
mNotifyMgr.notify(1, mBuilder.build());

【讨论】:

    【解决方案2】:

    我没有看到实际设置通知的方法。它应该看起来像这样:

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(mId, mBuilder.build());
    

    查看此链接,该链接描述了如何发送通知:http://developer.android.com/guide/topics/ui/notifiers/notifications.html

    归根结底,您的代码不完整。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多