آموزش های این وب سایت به صورت رایگان در دسترس است. اطلاعات بیشتر
مشکل عدم دسترسی خریداران پیشین به برخی آموزش ها برطرف شد
بروز خطا
   [message]
اشتراک در سوال
رای ها
[dataList]

فعال کردن سرویسی که هر چند ثانیه یک بار به سرور وصل بشه

mosafer  7 سال پیش  7 سال پیش
+2 0

با سلام

من برنامه ای دارم که در قسمت اخبار به وسیله یه سرویس بره سرور رو چک کنه که ببینه اخبار جدیدی امده یا نه که اگه امد نوتیفیکیشن بده

که قسمت سرویسم به این صورته :

 
public class MyService extends IntentService {

    public static Context           context;
    public static SharedPreferences preferences;
    private static final String     TAG = "MyService";

    DatabaseAcsan             db;
    private String strurl = null;


    public MyService() {
        super("MyWebRequestService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i("LOG", "Started service:))");
        context = getApplicationContext();
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Log.d(TAG, "onStart");
       
        db = new DatabaseAcsan(G.context);
        
        List<URLAdress> urlAdresses = db.getURL();

        for(int i=0; i <urlAdresses.size(); i++){
            
               strurl   = urlAdresses.get(i).AdressURL;
            Log.i(strurl, strurl);
        }   
        
        start();

    }


    private void start() {

        StringRequest request = new StringRequest(Request.Method.POST, strurl, new Response.Listener<String>() {

            private String tag_json_obj;
            private NewsMain task;
            private String strId;
            private String strTitr;
            private String strDate;

            @Override
            public void onResponse(String response) {

                Log.d("yes", response.toString());

                try {

                    JSONObject json = new JSONObject(response);
                    JSONArray jr = json.getJSONArray("Table1");

                    for (int i = 0; i < jr.length(); i++) {

                        JSONObject jsonObject = jr.getJSONObject(i);

                        task = new NewsMain(tag_json_obj, tag_json_obj, tag_json_obj, tag_json_obj, tag_json_obj);

                        strId = jsonObject.getString("NewsId");
                        task.NewsTitr = jsonObject.getString("NewsTitle");

                        String html = jsonObject.getString("NewsText");
                        html = html.replaceAll("<(.*?)\\>", " ");//Removes all items in brackets
                        html = html.replaceAll("<(.*?)\\\n", " ");//Must be undeneath
                        html = html.replaceFirst("(.*?)\\>", " ");//Removes any connected item to the last bracket
                        html = html.replaceAll("&nbsp;", " ");
                        html = html.replaceAll("&amp;", " ");

                        task.NewsText = html;
                        task.NewsLogo = jsonObject.getString("NewsPic");
                        task.NewsDate = jsonObject.getString("NewsDate");

                        strTitr = jsonObject.getString("NewsTitle");

                        strDate = jsonObject.getString("NewsDate");
                     
                        G.tasks.add(task);

                        if (db.getNewsId(strId) == true) {

                             Log.i("strId to service",  "خبر وجود دارد");


                        } else  if (db.getNewsId(strId) == false) {
                            
                            Notification(strId, task.NewsTitr,  task.NewsText, strDate);
                                  Log.i("Notification",  "Notification");
                                  
                        }
                        
                    }

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

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
                
            }
        }) {

            Map<String, String> params = new HashMap<String, String>();


            @Override
            protected Map<String, String> getParams() {
                params.put("id", "1");
                return params;
            }


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                params.put("id", "1");
                return params;
            }
        };

        RequestQueue queue = Volley.newRequestQueue(G.context);
        queue.add(request);

    }


    public void Notification(String NewsDate, String NewsTitle, String NewsText, String id) {

        //Uri uri = Uri.parse("market://details?id=" + link);
        //Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Intent Intent = new Intent(context, ActivityMain.class);
        //PendingIntent pIntent = PendingIntent.getService(context, 0, srvIntent, 0);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, Intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSound(alarmSound)
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker(NewsDate)
                .setContentTitle(NewsTitle)
                .setContentText(NewsText)
                .setContentIntent(pIntent)
                .setAutoCancel(true);

        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationmanager.notify(0, builder.build());

    }
}

 

و در صفحه اصلی برنامه این سرویس رو start زدم

  startService(new Intent(ActivityMain.this, MyService.class));

و برای اینکه سرویسم هر چند ثانیه یک بار کار بده و اخبار سرور رو زمانی که کاربر حتی از برنامه خارجه چک کنه ببینه اخبار جدیدی هست یا نه که اگه بود نوتیفیکیشن بده برای این کار من از  AlarmManager و BroadcastReceiver استفاده کردم.

به این شکل :

 public class Broadcast extends BroadcastReceiver {

    String strNews;

    int    Year;
    int    Month;
    int    Day;


    @Override
    public void onReceive(Context context, Intent intent) {

        //Intent background = new Intent(context, MyService.class);
        // context.startService(background);

        Log.i("no", "no");

        Calendar cal = Calendar.getInstance();
        Intent srvIntent = new Intent(context, MyService.class);
        PendingIntent pIntent = PendingIntent.getService(context, 0, srvIntent, 0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5000, pIntent);

    }

}

ولی این کارو نمیکنه یعنی هر 5 ثانیه یکبار...

دلیل چی میتونه باشه؟

اینم فایل منیفستم!

 
    <uses-sdk android:minSdkVersion="8"
        android:targetSdkVersion="18"/>
    
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
    

    <application
        android:name=".G"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true" >
        
        <receiver
            android:name=".Broadcast"
            android:enabled="true"
            android:exported="true" >
                      
        </receiver>
  <activity
            android:name=".ActivityMain"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:windowSoftInputMode="adjustPan|stateHidden" >
                </activity>

<service android:name=".MyService" > </service>

لطفا راهنماییم کنید ممنون میشم

+1 0
این همه کد!!! خودتون با LogCat چک کنید که چه جاهایی اجرا میشه و ببینید Warning یا چیز دیگه ای چاپ نمیشه؟ (7 سال پیش)
+1 0
یکی از علت هاش میتونه زمان کوتاهی باشه که برای آلارمتون قرار دادید. هر 5 ثانیه یک بار اگه بخواد این همه کار انجام بشه که اندروید قفل میکنه ! (دریافت اطلاعات از اینترنت کار زمان بری هست !) درضمن برای همچین دستوراتی که قراره هر چند ثانیه یک بار تکرار بشوند به نظر این حقیر بهتره که از TimerTask استفاده کنید ! (7 سال پیش)
 برای این سوال 1 پاسخ وجود دارد.
پاسخ به سوال 
mosafer  7 سال پیش
+1 0

من یه اشتباه کردم الان تصحیح شده و میذارم ببینید..

در  ActivityMain :

 

   Calendar cal = Calendar.getInstance();
         Intent srvIntent = new Intent(ActivityMain.this, Broadcast.class);
         srvIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         PendingIntent pendingIntent = PendingIntent.getBroadcast(ActivityMain.this, 0, srvIntent, PendingIntent.FLAG_CANCEL_CURRENT);
         AlarmManager alarm = (AlarmManager) ActivityMain.this.getSystemService(Context.ALARM_SERVICE);

        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);
       
         Log.d("MyActivity", "Set alarmManager.setRepeating to: " + cal.getTime().toLocaleString());
 

 

در  Broadcast :

  @Override
    public void onReceive(Context context, Intent intent) {
                   
        Intent dailyUpdater = new Intent(G.context, MyService.class);
        context.startService(dailyUpdater);
        Log.d("Broadcast", "Called context.startService from Broadcast.onReceive");       
    }
 

 

و در سرویسم :

  public class MyService extends IntentService {

    public static Context           context;
    public static SharedPreferences preferences;
    private static final String     TAG = "MyService";

    DatabaseAcsan             db;
    private String strurl = null;


    public MyService() {
        super("MyWebRequestService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i("LOG", "Started service:))");
        context = getApplicationContext();
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Log.d(TAG, "onStart");
       
        db = new DatabaseAcsan(G.context);
        
        List<URLAdress> urlAdresses = db.getURL();

        for(int i=0; i <urlAdresses.size(); i++){
            
               strurl   = urlAdresses.get(i).AdressURL;
            Log.i(strurl, strurl);
        }   
        
        start();

    }


    private void start() {

        StringRequest request = new StringRequest(Request.Method.POST, strurl, new Response.Listener<String>() {

            private String tag_json_obj = null;
            private NewsMain task;
            private String strId = null;
            private String strTitr = "";
            private String strDate = null;
                    

            @Override
            public void onResponse(String response) {

                Log.d("yes", response.toString());

                try {
                    
                    JSONObject json = new JSONObject(response);
                    JSONArray jr = json.getJSONArray("Table1");
                    Log.d("Table1", jr.toString());
                    
                  //  int profile_counts = db.getProfilesCount();
                    
                    
                  //  if (profile_counts > 0) {

                        for (int i = 0; i < jr.length(); i++) {

                            JSONObject jsonObject = jr.getJSONObject(i);

                            task = new NewsMain(tag_json_obj, tag_json_obj, tag_json_obj, tag_json_obj, tag_json_obj);

                            strId = jsonObject.getString("NewsId");
                            task.NewsTitr = jsonObject.getString("NewsTitle");

                            String html = jsonObject.getString("NewsText");
                            html = html.replaceAll("<(.*?)\\>", " ");//Removes all items in brackets
                            html = html.replaceAll("<(.*?)\\\n", " ");//Must be undeneath
                            html = html.replaceFirst("(.*?)\\>", " ");//Removes any connected item to the last bracket
                            html = html.replaceAll("&nbsp;", " ");
                            html = html.replaceAll("&hellip;", " ");
                            html = html.replaceAll("&zwnj;", " ");
                            html = html.replaceAll("&ndash;", " ");
                            html = html.replaceAll("&laquo;", " ");
                            html = html.replaceAll("&amp;", " ");

                            task.NewsText = html;
                            task.NewsLogo = jsonObject.getString("NewsPic");
                            task.NewsDate = jsonObject.getString("NewsDate");

                            strTitr = jsonObject.getString("NewsTitle");

                            strDate = jsonObject.getString("NewsDate");

                            //Log.i("log : ", task.NewsTitr);

                            //Log.i("newsNew : ",jsonObject.getString("NewsDate"));
                         
                            
                            if (db.getNewsId(strId) == true) {

                                 Log.i("strId to service",  strId);


                            } else  if (db.getNewsId(strId) == false) {

                                Notification(task.NewsTitr ,strId, task.NewsText, strDate);
                                Log.i("Notification",  "Notification");   
                                
                                DateNews dateNews = new DateNews();

                                dateNews.NewsID = strId;
                                dateNews.NewsTitr = strTitr;
                                dateNews.NewsDate = strDate;

                                // news.NewsId=task.NewsId;
                                boolean result = db.addNews(dateNews);

                                if (result == true) {

                                   //  Toast.makeText(getActivity(), "news Success2", Toast.LENGTH_SHORT).show();  
                                    Log.e("LOG service ", " news Success");

                                }
                                else
                                {
                                    // Toast.makeText(getActivity(), "news Not Success", Toast.LENGTH_SHORT).show();
                                    Log.e("LOG service", "news Not Success");

                                }

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

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
                
            }
        }) {

            Map<String, String> params = new HashMap<String, String>();


            @Override
            protected Map<String, String> getParams() {
                params.put("id", "1");
                return params;
            }


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                params.put("id", "1");
                return params;
            }
        };

        RequestQueue queue = Volley.newRequestQueue(G.context);
        queue.add(request);

    }


    public void Notification(String NewsDate, String NewsTitle, String NewsText, String id) {

        //Uri uri = Uri.parse("market://details?id=" + link);
        //Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Intent Intent = new Intent(context, ActivityMain.class);
        //PendingIntent pIntent = PendingIntent.getService(context, 0, srvIntent, 0);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, Intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSound(alarmSound)
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker(NewsDate)
                .setContentTitle(NewsTitle)
                .setContentText(NewsText)
                .setContentIntent(pIntent)
                .setAutoCancel(true);

        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationmanager.notify(0, builder.build());

    }
}
 

 


پاسخگویی و مشاهده پاسخ های این سوال تنها برای اعضای ویژه سایت امکان پذیر است .
چنانچه تمایل دارید به همه بخش ها دسترسی داشته باشید میتوانید از این بخش لایسنس این آموزش را خریداری نمایید .