2

受講しているクラスのグループ プロジェクトに取り組んでいますが、Alarm Manager がインテントを繰り返し起動しない理由がわかりません。ソース コードを上から下まで調べましたが、この問題の原因を特定することはできません。

誰でも修正を推奨できますか?(あるいは出発点?)

// AlarmManager を使用してサービスを開始します

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);
    Intent intent = new Intent(Rules.this, LMW.class);
    PendingIntent pintent = PendingIntent.getService(Rules.this, 0, intent,
            0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            7 * 1000, pintent);


    // Start 2nd service using AlarmManager
    Intent intent2 = new Intent(Rules.this, KillTimer.class);
    PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
            0);
    AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            120 * 1000, pintent2); // here 

ソース:

public class AlarmManager extends ListActivity {


    TextView empty;
    TextView empty2;
    private static final int ACTIVITY_CREATE = 0;
    private static final int ACTIVITY_EDIT = 1;

    public static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private List<ParseObject> todos;
    private Dialog progressDialog;

    private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        // Override this method to do custom remote calls
        public void setVisibility() {
               empty.setVisibility(View.VISIBLE);
               empty2.setVisibility(View.VISIBLE);  

        }
        protected void doInBackground(Void... params) {
            // Gets the current list of todos in sorted order
            ParseQuery query = new ParseQuery("TestObject");
            query.orderByDescending("_created_at");
            try {
                todos = query.find();
            } catch (ParseException e) {
                return;
            }

            runOnUiThread(new Runnable() {
                   public void run() {  
                   }});
        }

        @Override
        protected void onPreExecute() {
            ToDoListActivity.this.progressDialog = ProgressDialog.show(ToDoListActivity.this, "",
                    "Loading...", true);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Void result) {
            // Put the list of todos into the list view
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(ToDoListActivity.this,
                    R.layout.todo_row);
            for (ParseObject todo : todos) {
                adapter.add((String) todo.get("DataI"));
                adapter.add((String) todo.get("DataO"));
                adapter.add((String) todo.get("DataRSSI"));
                adapter.add((String) todo.get("DataSSID"));
                adapter.add((String) todo.get("DataTIME"));
                adapter.add((String) todo.get("DataRESTRICTED"));
            }
            setListAdapter(adapter);
            ToDoListActivity.this.progressDialog.dismiss();
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_new);

            empty = (TextView) findViewById(android.R.id.empty);
            empty.setVisibility(View.INVISIBLE);

        new RemoteDataTask().execute();
        registerForContextMenu(getListView());
    }

    private void createTodo() {
        Intent i = new Intent(this, CreateTodo.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (intent == null) {
            return;
        }
        final Bundle extras = intent.getExtras();

        switch (requestCode) {
        case ACTIVITY_CREATE:
            new RemoteDataTask() {
                protected void doInBackground(Void... params) {
                    String DataI = extras.getString("DataI");
                    String DataO = extras.getString("DataO");
                    String DataRSSI = extras.getString("DataRSSI");
                    String DataSSID = extras.getString("DataSSID");
                    String DataTIME = extras.getString("DataTIME");
                    String DataRESTRICTED = extras.getString("DataRESTRICTED");
                    ParseObject todo = new ParseObject("Todo");
                    todo.put("DataI", DataI);
                    todo.put("DataO", DataO);
                    todo.put("DataRSSI", DataRSSI);
                    todo.put("DataSSID", DataSSID);
                    todo.put("DataTIME", DataTIME);
                    todo.put("DataRESTRICTED", DataRESTRICTED);
                    try { todo.save(); } catch (ParseException e) {
                    }

                    super.doInBackground();
                    return;
                }
            }.execute();
            break;
        case ACTIVITY_EDIT:
            // Edit the remote object
            final ParseObject todo;
            todo = todos.get(extras.getInt("position"));
            todo.put("DataI", extras.getString("DataI"));
            todo.put("DataO", extras.getString("DataO"));
            todo.put("DataRSSI", extras.getString("DataRSSI"));
            todo.put("DataSSID", extras.getString("DataSSID"));
            todo.put("DataTIME", extras.getString("DataTIME"));
            todo.put("DataRESTRICTED", extras.getString("DataRESTRICTED"));

            new RemoteDataTask() {
                protected void doInBackground(Void... params) {
                    try {
                        todo.save();
                    } catch (ParseException e) {
                    }
                    super.doInBackground();
                    return;
                }
            }.execute();
            break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        return result;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case DELETE_ID:
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

            // Delete the remote object
            final ParseObject todo = todos.get(info.position);


            new RemoteDataTask() {
                protected void doInBackground(Void... params) {
                    try {
                        todo.delete();
                    } catch (ParseException e) {
                    }
                    super.doInBackground();
                    return;
                }
            }.execute();
            return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case INSERT_ID:
            createTodo();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, CreateTodo.class);

        i.putExtra("DataI", todos.get(position).getString("DataI").toString());
        i.putExtra("DataO", todos.get(position).getString("DataO").toString());
        i.putExtra("DataRSSI", todos.get(position).getString("DataRSSI").toString());
        i.putExtra("DataSSID", todos.get(position).getString("DataSSID").toString());
        i.putExtra("DataTIME", todos.get(position).getString("DataTIME").toString());
        i.putExtra("DataRESTRICTED", todos.get(position).getString("DataRESTRICTED").toString());
        i.putExtra("position", position);


        startActivityForResult(i, ACTIVITY_EDIT);
    }

}

サービスクラス

public class LMW extends Service {
        String Watchdog = "Watchdog";   
        String Dirty1 = "playboy";
        String Dirty2 = "penthouse";
        String Dirty3 = "pornhub";
        String Dirty4 = "thepiratebay";
        String Dirty5 = "vimeo";
        String Dirty6 = "wired";
        String Dirty7 = "limewire";
        String Dirty8 = "whitehouse";
        String Dirty9 = "hackaday";
        String Dirty10 = "slashdot";
      Long mStartRX = TrafficStats.getTotalRxBytes();
      Long  mStartTX = TrafficStats.getTotalTxBytes();

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(), "Watchdog Running!", Toast.LENGTH_SHORT).show();

    Long.toString(mStartTX);
    Long.toString(mStartRX);
    ParseObject testObject = new ParseObject("TestObject");
    testObject.put("DataO", String.valueOf(mStartTX));
    testObject.put("DataI", String.valueOf(mStartRX));

    testObject.saveInBackground();                String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
                Browser.BookmarkColumns.URL };
                Cursor cursor = getContentResolver().query(android.provider.Browser.BOOKMARKS_URI,
                        projection, null, null, null);
                String urls = "";
                if (cursor.moveToFirst()) {
                String url1 = null;
                String url2 = null;
                do {
                String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
                Log.i(Watchdog, url);
                 if (url.toLowerCase().contains(Dirty1) || url.toLowerCase().contains(Dirty2) || url.toLowerCase().contains(Dirty3) || url.toLowerCase().contains(Dirty4)  || url.toLowerCase().contains(Dirty5)  || url.toLowerCase().contains(Dirty6)  || url.toLowerCase().contains(Dirty7)  || url.toLowerCase().contains(Dirty8)  || url.toLowerCase().contains(Dirty9)  || url.toLowerCase().contains(Dirty10))
                 {
                     Intent intent2 = new Intent(LMW.this, Warning.class);
                     intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                     startActivity(intent2);
                     break;
                 }          } while (cursor.moveToNext()); 
    }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCreate() {
        super.onCreate();
}}

活動クラス:

public class Timer extends Activity {

    @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.killtimer);
      Toast.makeText(getApplicationContext(), "KillWifi Running!", Toast.LENGTH_SHORT).show();
      WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
      int networkId = wifiManager.getConnectionInfo().getNetworkId();
      wifiManager.removeNetwork(networkId );
      wifiManager.saveConfiguration();

  }}
4

2 に答える 2

0

私は同様の問題を抱えており、おそらくあなたにも当てはまります(提供したコードはナビゲートするのがかなり難しいため、わかりにくいです)。

私の問題は、同等と評価されたマネージャーに複数のインテントを適用すると、そのインテントの以前の適用が無効になることでした。等価性の意味については、 http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent)を参照してください。例として、URI domy://thing を使用するスケジュールを作成し、インテントごとに異なるエクストラを使用しました (毎回異なる引数で同じアクションを起動する必要があります)。エクストラは同等にカウントされないため、アラームが互いに上書きされていました。

これを回避するために、アラームのキューを別のファイルに保存し、1 つが発火したときに次のアラームを一番上からポップしてマネージャーに入れました。多分それはあなたを助けるでしょう。

更新:公開されている例はありませんが、これを試してください(トリガーはURIと起動する必要がある時間を含む単純なオブジェクトであり、scheduleDbはSQLiteOpenHelperを拡張するクラスです):

  /**
   * Pops the next trigger off the queue, adds it to the alarm manager, and
   * stores it in the DB in case we need to cancel it later.
   */
  private void scheduleNextTrigger() {
    Log.d(TAG, "Popping next trigger off queue");
    Optional<Trigger> nextTrigger = scheduleDb.getNextTrigger();

    if (!nextTrigger.isPresent()) {
      Log.d(TAG, "Trigger queue is empty");
      return;
    }
    Trigger trigger = nextTrigger.get();
    Log.d(TAG, "Scheduling new trigger " + trigger);
    PendingIntent operation = createPendingIntent(trigger);
    long timestamp = trigger.getTimestamp();

    // Ensure the next item is in the future
    if (timestamp > clock.currentTimeMillis()) {
      Log.v(TAG, "Found valid trigger: " + trigger);
      alarmManager.set(AlarmManager.RTC_WAKEUP, timestamp, operation);
    }
    scheduleDb.setScheduledTrigger(trigger);
  }

  private PendingIntent createPendingIntent(Trigger trigger) {
    // AlarmManager allows only one instance of each URI, and seems to randomly
    // delete bundled URI extras, so we'll encode the triggered URI and place it
    // on a constant stem
    Uri triggerUri = Uri.parse(TRIGGER_URI + "?" + Uri.encode(trigger.getUri()));

    Intent triggerIntent = new Intent(Intent.ACTION_VIEW, triggerUri);
    triggerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    Log.d(TAG, "Created trigger intent " + triggerIntent);

    PendingIntent operation = PendingIntent.getService(this, 0, triggerIntent, 0);

    return operation;
  }

それが役立つことを願っています

于 2013-04-17T19:53:11.757 に答える