<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
+ <uses-permission android:name="de.android.mobiads.MOBIADSRECEIVER" />
<application
android:icon="@drawable/ic_launcher" android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="touchscreen|keyboard"
android:noHistory="true"
- android:taskAffinity="de.android.mobiads.list">
+ android:excludeFromRecents="true"
+ android:taskAffinity="de.android.mobiads.list"
+ android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MOBIADSNEWADS" />
<category android:name="android.intent.category.DEFAULT" />
}
public static final class string {
public static final int alert_dialog_logged=0x7f050004;
+ public static final int alert_dialog_not_logged=0x7f050005;
public static final int app_description=0x7f050003;
public static final int app_name=0x7f050002;
- public static final int button_cancel=0x7f050010;
- public static final int button_localads=0x7f050011;
- public static final int button_login=0x7f050009;
- public static final int button_messagebind=0x7f05000a;
- public static final int button_messagelistlocalads=0x7f05000e;
- public static final int button_messagestartservice=0x7f05000d;
- public static final int button_messagestopservice=0x7f05000c;
- public static final int button_messageunbind=0x7f05000b;
- public static final int button_ok=0x7f05000f;
- public static final int desc=0x7f05001d;
- public static final int encoded_web_service=0x7f05001c;
- public static final int error_dialog_connection_error=0x7f050005;
- public static final int error_dialog_no_local_ads=0x7f050021;
- public static final int error_dialog_userpwd_error=0x7f050006;
+ public static final int button_cancel=0x7f050011;
+ public static final int button_localads=0x7f050012;
+ public static final int button_login=0x7f05000a;
+ public static final int button_messagebind=0x7f05000b;
+ public static final int button_messagelistlocalads=0x7f05000f;
+ public static final int button_messagestartservice=0x7f05000e;
+ public static final int button_messagestopservice=0x7f05000d;
+ public static final int button_messageunbind=0x7f05000c;
+ public static final int button_ok=0x7f050010;
+ public static final int desc=0x7f05001e;
+ public static final int encoded_web_service=0x7f05001d;
+ public static final int error_dialog_connection_error=0x7f050006;
+ public static final int error_dialog_no_local_ads=0x7f050022;
+ public static final int error_dialog_userpwd_error=0x7f050007;
public static final int header_bar=0x7f050000;
- public static final int menuads_login=0x7f050020;
- public static final int menuads_remove=0x7f05001e;
- public static final int menuads_settings=0x7f05001f;
+ public static final int menuads_login=0x7f050021;
+ public static final int menuads_remove=0x7f05001f;
+ public static final int menuads_settings=0x7f050020;
public static final int new_ads=0x7f050001;
- public static final int password=0x7f050008;
- public static final int remote_service_content_empty_notification=0x7f050015;
- public static final int remote_service_content_notification=0x7f050014;
- public static final int remote_service_new_ads=0x7f050012;
- public static final int remote_service_received_ad_notification=0x7f050013;
- public static final int remote_service_started_notification=0x7f050016;
- public static final int remote_service_stopped_notification=0x7f050017;
- public static final int remote_service_title_notification=0x7f050018;
- public static final int url_login_web_service=0x7f050019;
- public static final int url_web=0x7f05001a;
- public static final int user_agent_web_service=0x7f05001b;
- public static final int username=0x7f050007;
+ public static final int password=0x7f050009;
+ public static final int remote_service_content_empty_notification=0x7f050016;
+ public static final int remote_service_content_notification=0x7f050015;
+ public static final int remote_service_new_ads=0x7f050013;
+ public static final int remote_service_received_ad_notification=0x7f050014;
+ public static final int remote_service_started_notification=0x7f050017;
+ public static final int remote_service_stopped_notification=0x7f050018;
+ public static final int remote_service_title_notification=0x7f050019;
+ public static final int url_login_web_service=0x7f05001a;
+ public static final int url_web=0x7f05001b;
+ public static final int user_agent_web_service=0x7f05001c;
+ public static final int username=0x7f050008;
}
public static final class xml {
public static final int preferences=0x7f040000;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="right"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:weightSum="1">
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:orientation="vertical" >
<FrameLayout
android:id="@+id/frameLayout1"
</FrameLayout>
<EditText
+ style="@android:style/Theme.Black"
+ android:editTextColor="@android:color/primary_text_light"
+ android:editTextBackground="@android:drawable/edit_text"
android:id="@+id/username"
android:singleLine="true"
android:layout_width="fill_parent"
android:hint="@string/username"/>
<EditText
+ style="@android:style/Theme.Black"
android:id="@+id/password"
android:inputType="textPassword"
android:singleLine="true"
android:title="@string/menuads_login"
android:titleCondensed="@string/menuads_login"
android:showAsAction="ifRoom|withText"
- android:alphabeticShortcut="string"
- android:numericShortcut="string"
android:checkable="false"
android:visible="true"
android:enabled="true" />
android:titleCondensed="@string/menuads_settings"
android:visible="true"
android:checkable="false"
- android:enabled="false"
+ android:enabled="true"
android:showAsAction="ifRoom|withText"/>
<!-- I want overflow menu button if there is no room: android:showAsAction="ifRoom|withText" -->
<string name="app_name">MobiAds</string>
<string name="app_description">Receive notifications about offers and discounts.</string>
<string name="alert_dialog_logged">You are already logged in</string>
+ <string name="alert_dialog_not_logged">You are not logged in</string>
<string name="error_dialog_connection_error">Connection error with MobiAds server.</string>
<string name="error_dialog_userpwd_error">The username or password you entered is incorrect.</string>
<string name="username">Username</string>
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
+
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
+
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
currentPolicy = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
setContentView(R.layout.login);
+
}
public void onClickLogin(View v) {
HttpResponse httpResponse = null;
final List<NameValuePair> formParams = new ArrayList<NameValuePair>(2);
+ Cookie.setCookie("gugugu");
+
httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, getResources().getString(R.string.encoded_web_service));
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getResources().getString(R.string.user_agent_web_service));
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
+++ /dev/null
-package de.android.mobiads;
-
-import android.app.Activity;
-import android.app.ActivityManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.app.FragmentManager;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.preference.CheckBoxPreference;
-import android.preference.Preference;
-import android.preference.PreferenceFragment;
-import de.android.mobiads.list.MobiAdsList.MobiAdsListFragment;
-
-public class MobiAdsPreferences extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- FragmentManager fm = getFragmentManager();
-
- // Create the list fragment and add it as our sole content.
- if (fm.findFragmentById(android.R.id.content) == null) {
- MobiAdsListFragment list = new MobiAdsListFragment();
- fm.beginTransaction().add(android.R.id.content, list).commit();
- }
-
-
- }
-
- public static class MobiAdsPreferencesFragment extends PreferenceFragment {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- // Load the preferences from an XML resource
- addPreferencesFromResource(R.xml.preferences);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference("service_started");
- checkBoxPreference.setChecked(isMyServiceRunning());
- checkBoxPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
-
- @Override
- public boolean onPreferenceClick(Preference preference) {
- CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preference;
- if (checkBoxPreference.isChecked()) {
- Intent intent = new Intent(getActivity(), MobiAdsService.class);
- intent.putExtra("cookie", Cookie.getCookie());
- getActivity().startService(intent);
- }
- else {
- getActivity().stopService(new Intent(getActivity(), MobiAdsService.class));
- }
- return false;
- }
- });
- }
-
- private boolean isMyServiceRunning() {
- ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if (MobiAdsService.class.getName().equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
- }
-}
package de.android.mobiads;
-import de.android.mobiads.batch.MobiAdsBatch;
-import de.android.mobiads.list.MobiAdsLatest;
-import de.android.mobiads.list.MobiAdsLatestList;
-import de.android.mobiads.list.MobiAdsNewAdsActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
+import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
+import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
+import de.android.mobiads.batch.MobiAdsBatch;
+import de.android.mobiads.list.MobiAdsLatestList;
public class MobiAdsService extends Service {
private MobiAdsBatch mobiAdsBatch;
}
}
+ private final BroadcastReceiver receiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ //This will be run in the main thread of this service. It might be interesting to use a Hanlder
+ //for this receiver implemeting its own thread. :/
+ //TODO: If I do not want to have any trouble, to use a synchronize to access this code here and when
+ //receiving new ads. Besides you are using the same code xD. No time right now. I must improve my code
+ //but I am in a hurry.
+ int noReadCount = 0;
+ CharSequence contentText;
+ if ((noReadCount = mobiAdsBatch.noReadAdsCount()) == 0) {
+ contentText = getText(R.string.remote_service_content_empty_notification);
+ showNotification(0, noReadCount, contentText, null);
+ }
+ else {
+ contentText = getText(R.string.remote_service_content_notification);
+ showNotification(0, noReadCount, contentText, MobiAdsLatestList.class);
+ }
+ }
+ };
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification(0, noReadCount, contentText, MobiAdsLatestList.class);
}
+
+ IntentFilter filter = new IntentFilter();
+ filter.addAction("de.android.mobiads.MOBIADSRECEIVER");
+ registerReceiver(receiver, filter);
+
+
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
+ unregisterReceiver(receiver);
+
// Cancel the persistent notification.
notificationManager.cancel(R.string.remote_service_title_notification);
package de.android.mobiads;
+import de.android.mobiads.MobiAdsTabsActivity.AlertDialogFragment;
+import de.android.mobiads.list.MobiAdsList;
import android.app.Activity;
import android.app.ActivityManager;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.FragmentManager;
import android.content.Context;
+import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
public boolean onPreferenceClick(Preference preference) {
CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preference;
if (checkBoxPreference.isChecked()) {
- Intent intent = new Intent(getActivity(), MobiAdsService.class);
- intent.putExtra("cookie", Cookie.getCookie());
- getActivity().startService(intent);
+ if (Cookie.getCookie() != null) {
+ Intent intent = new Intent(getActivity(), MobiAdsService.class);
+ intent.putExtra("cookie", Cookie.getCookie());
+ getActivity().startService(intent);
+ }
+ else {
+ DialogFragment newFragment = MobiAdsList.AlertDialogFragment.newInstance(R.string.alert_dialog_not_logged);
+ newFragment.show(getFragmentManager(), "alertDialog");
+ checkBoxPreference.setChecked(false);
+ }
}
else {
getActivity().stopService(new Intent(getActivity(), MobiAdsService.class));
return false;
}
}
+
+
}
+++ /dev/null
-package de.android.mobiads;
-
-import de.android.mobiads.list.MobiAdsList;
-import android.app.ActionBar;
-import android.app.Activity;
-import android.app.ActivityManager;
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.DialogFragment;
-import android.app.Fragment;
-import android.app.FragmentTransaction;
-import android.app.ActionBar.Tab;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.os.Bundle;
-
-public class MobiAdsTabsActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- final ActionBar bar = getActionBar();
- bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
- bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
- bar.setTitle(getResources().getString(R.string.header_bar));
-
- bar.addTab(bar.newTab()
- .setText("Local Ads")
- .setTabListener(new TabListener<MobiAdsList.MobiAdsListFragment>(
- this, "localads", MobiAdsList.MobiAdsListFragment.class)));
-
- if (Cookie.getCookie() != null || isMyServiceRunning()) {
- bar.addTab(bar.newTab()
- .setText("Control Panel")
- .setTabListener(new TabListener<MobiAdsPreferences.MobiAdsPreferencesFragment>(
- this, "controlpanel", MobiAdsPreferences.MobiAdsPreferencesFragment.class)));
- }
-
- bar.addTab(bar.newTab()
- .setText("Login")
- .setTabListener(new Login()));
-
-
-
- if (savedInstanceState != null) {
- bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- if ((Cookie.getCookie() != null) && (getActionBar().getTabCount() == 2)) {
- getActionBar().addTab(getActionBar().newTab()
- .setText("Control Panel")
- .setTabListener(new TabListener<MobiAdsPreferences.MobiAdsPreferencesFragment>(
- this, "controlpanel", MobiAdsPreferences.MobiAdsPreferencesFragment.class)), 1);
-
- }
- }
-
- public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
- private final Activity mActivity;
- private final String mTag;
- private final Class<T> mClass;
- private final Bundle mArgs;
- private Fragment mFragment;
-
- public TabListener(Activity activity, String tag, Class<T> clz) {
- this(activity, tag, clz, null);
- }
-
- public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
- mActivity = activity;
- mTag = tag;
- mClass = clz;
- mArgs = args;
-
- // Check to see if we already have a fragment for this tab, probably
- // from a previously saved state. If so, deactivate it, because our
- // initial state is that a tab isn't shown.
- mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
- if (mFragment != null && !mFragment.isDetached()) {
- FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
- ft.detach(mFragment);
- ft.commit();
- }
- }
-
- public void onTabSelected(Tab tab, FragmentTransaction ft) {
- if (mFragment == null) {
- mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
- ft.add(android.R.id.content, mFragment, mTag);
- } else {
- ft.attach(mFragment);
- }
- }
-
- public void onTabUnselected(Tab tab, FragmentTransaction ft) {
- if (mFragment != null) {
- ft.detach(mFragment);
- }
- }
-
- public void onTabReselected(Tab tab, FragmentTransaction ft) {
- //Nothing to do here.
- }
- }
-
- private class Login implements ActionBar.TabListener {
-
- @Override
- public void onTabSelected(Tab tab, FragmentTransaction ft) {
- if (Cookie.getCookie() != null) {
- createAlertDialog(R.string.alert_dialog_logged);
- }
- else {
- Intent intent = new Intent("android.intent.action.MOBIADS").
- setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.MobiAdsLoginActivity"));
- startActivity(intent);
- }
- }
-
- @Override
- public void onTabUnselected(Tab tab, FragmentTransaction ft) {
- //Nothing to do here
- }
-
- @Override
- public void onTabReselected(Tab tab, FragmentTransaction ft) {
-
- if (Cookie.getCookie() != null) {
- createAlertDialog(R.string.alert_dialog_logged);
- }
- else {
- Intent intent = new Intent("android.intent.action.MOBIADS").
- setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.MobiAdsLoginActivity"));
- startActivity(intent);
- }
- }
- }
-
- private void createAlertDialog(int title) {
- DialogFragment newFragment = AlertDialogFragment.newInstance(title);
- newFragment.show(getFragmentManager(), "alertDialog");
- }
-
- public static class AlertDialogFragment extends DialogFragment {
-
- public static AlertDialogFragment newInstance(int title) {
- AlertDialogFragment frag = new AlertDialogFragment();
- Bundle args = new Bundle();
-
- args.putInt("title", title);
- frag.setArguments(args);
-
- return frag;
- }
-
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- int title = getArguments().getInt("title");
-
- return new AlertDialog.Builder(getActivity())
- .setIcon(android.R.drawable.ic_dialog_alert)
- .setTitle(title)
- .setPositiveButton(R.string.button_ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
-
- }
- }
- )
- .create();
- }
- }
-
- private boolean isMyServiceRunning() {
- ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if (MobiAdsService.class.getName().equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
-}
\ No newline at end of file
import android.util.Log;
import de.android.mobiads.MobiAdsService;
import de.android.mobiads.R;
-import de.android.mobiads.list.MobiAdsNewAdsActivity;
+import de.android.mobiads.list.MobiAdsLatestList;
import de.android.mobiads.provider.Indexer;
public class MobiAdsBatch {
getText(R.string.remote_service_content_notification);
}
((MobiAdsService)MobiAdsBatch.this.context).
- showNotification(0, noReadCount, contentText, MobiAdsNewAdsActivity.class);
+ showNotification(0, noReadCount, contentText, MobiAdsLatestList.class);
} catch (Throwable e1) {
//In case of any error, remove the index database and the file
+++ /dev/null
-package de.android.mobiads.list;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import de.android.mobiads.MobiAdsService;
-import de.android.mobiads.R;
-import de.android.mobiads.provider.Indexer;
-import android.app.Activity;
-import android.app.ActivityManager;
-import android.app.ListFragment;
-import android.app.LoaderManager;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.content.AsyncTaskLoader;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.Intent;
-import android.content.Loader;
-import android.database.Cursor;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.net.Uri;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseBooleanArray;
-import android.view.ActionMode;
-import android.view.LayoutInflater;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.ImageView;
-import android.widget.ListView;
-import android.widget.SearchView;
-import android.widget.TextView;
-import android.widget.AbsListView.MultiChoiceModeListener;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.SearchView.OnQueryTextListener;
-
-public class MobiAdsLatest extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setContentView(R.layout.latest_ads);
- }
-
- public static class MobiAdsListFragment extends ListFragment implements OnQueryTextListener,
- LoaderManager.LoaderCallbacks<List<AdsEntry>> {
- AdsEntryAdapter mAdapter;
- // If non-null, this is the current filter the user has provided.
- String mCurFilter;
-
-
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
-
- ListView listView = getListView();
-
- listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
-
- listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
-
- @Override
- public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
- final int checkedCount = getListView().getCheckedItemCount();
- switch (checkedCount) {
- case 0:
- mode.setSubtitle(null);
- break;
- case 1:
- mode.setSubtitle("One item selected");
- break;
- default:
- mode.setSubtitle("" + checkedCount + " items selected");
- break;
- }
- }
-
-
- @Override
- public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
- // Respond to clicks on the actions in the CAB
- switch (item.getItemId()) {
- case R.id.selectedmenu_remove:
- SparseBooleanArray itemsPositions = getListView().getCheckedItemPositions();
- Collection<AdsEntry> aux = new ArrayList<AdsEntry>(mAdapter.getCount());
- for (int i=0; i< itemsPositions.size(); i++) {
- if (itemsPositions.valueAt(i)) {
- aux.add(mAdapter.getItem(itemsPositions.keyAt(i)));
- }
- }
- if (!aux.isEmpty()) {
- for(final AdsEntry entry : aux) {
- removeAd(entry);
- }
- }
- mode.finish(); // Action picked, so close the CAB
- return true;
- default:
- return false;
- }
- }
-
- @Override
- public boolean onCreateActionMode(ActionMode mode, Menu menu) {
- MenuInflater inflater = mode.getMenuInflater();
- inflater.inflate(R.menu.menuads, menu);
- final int checkedCount = getListView().getCheckedItemCount();
- switch (checkedCount) {
- case 0:
- mode.setSubtitle(null);
- break;
- case 1:
- mode.setSubtitle("One item selected");
- break;
- default:
- mode.setSubtitle("" + checkedCount + " items selected");
- break;
- }
- return true;
- }
-
- @Override
- public void onDestroyActionMode(ActionMode mode) {
- //TODO: Save state (checked items) in orde to keep them when coming back from
- //the home screen.
- }
-
- @Override
- public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
- // Here you can perform updates to the CAB due to
- // an invalidate() request
- return false;
- }
- });
-
-
- listView.setOnItemClickListener(new OnItemClickListener() {
-
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- Uri uri = Uri.parse(mAdapter.getItem(position).getURL());
- startActivity(new Intent(Intent.ACTION_VIEW, uri));
- }
- });
-
- setEmptyText("No downloaded Ads.");
-
- // We have a menu item to show in action bar.
- setHasOptionsMenu(true);
-
-
- mAdapter = new AdsEntryAdapter(getActivity(), R.layout.ads_entry_list_item);
-
- setListAdapter(mAdapter);
- // Start out with a progress indicator.
- setListShown(false);
-
- // Prepare the loader. Either re-connect with an existing one,
- // or start a new one.
- //TODO: reload just if there are changes in the data base :/
- //getLoaderManager().initLoader(0, null, this);
- getLoaderManager().restartLoader(0, null, this);
- }
-
- private void removeAd(AdsEntry entry){
- int idAd = entry.getIdAd();
- Uri uriDelete = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" + "/idad/" + idAd);
-
- getActivity().getContentResolver().delete(uriDelete, null, null);
- mAdapter.remove(entry);
- mAdapter.notifyDataSetChanged();
- }
-
- @Override
- public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
- // Place an action bar item for searching.
- MenuItem item = menu.add("Search");
- item.setIcon(android.R.drawable.ic_menu_search);
- item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
- SearchView sv = new SearchView(getActivity());
- sv.setOnQueryTextListener(this);
- item.setActionView(sv);
- }
-
- @Override
- public Loader<List<AdsEntry>> onCreateLoader(int id, Bundle args) {
- // This is called when a new Loader needs to be created. This
- // sample only has one Loader with no arguments, so it is simple.
- return new AdsListLoader(getActivity());
- }
-
- @Override
- public void onLoadFinished(Loader<List<AdsEntry>> loader, List<AdsEntry> data) {
- mAdapter.setData(data);
-
- // The list should now be shown.
- if (isResumed()) {
- setListShown(true);
- } else {
- setListShownNoAnimation(true);
- }
-
- if (isMyServiceRunning()) {
- showNotification(0, 0, getText(R.string.remote_service_content_empty_notification));
- }
- }
-
- @Override
- public void onLoaderReset(Loader<List<AdsEntry>> loader) {
- mAdapter.setData(null);
- }
-
- @Override
- public boolean onQueryTextSubmit(String query) {
- // Don't care about this.
- return true;
- }
-
- @Override
- public boolean onQueryTextChange(String newText) {
- // Called when the action bar search text has changed. Update
- // the search filter, and restart the loader to do a new query
- // with this filter.
- mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
- getLoaderManager().restartLoader(0, null, this);
- return true;
- }
-
- private boolean isMyServiceRunning() {
- ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if (MobiAdsService.class.getName().equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
-
- public void showNotification(final int level, final int noReadAds, CharSequence contentText) {
- NotificationManager notificationManager = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
-
- // Set the icon, scrolling text and timestamp
- Notification.Builder notificationBuilder = new Notification.Builder(getActivity().getApplicationContext()).
- setSmallIcon(R.drawable.wheelnotification, level).
- setTicker(getText(R.string.remote_service_started_notification)).
- setWhen(System.currentTimeMillis()).
- setContentText(contentText).
- setContentTitle(getText(R.string.remote_service_title_notification)).
- setNumber(noReadAds);
- Notification notification = notificationBuilder.getNotification();
- notification.flags |= Notification.FLAG_NO_CLEAR;
-
- // Send the notification.
- // We use a string id because it is a unique number. We use it later to cancel.
- notificationManager.notify(R.string.remote_service_title_notification, notification);
- }
- }
-
-
- public static class AdsEntryAdapter extends ArrayAdapter<AdsEntry> {
- private final int adsItemLayoutResource;
-
- public AdsEntryAdapter(final Context context, final int adsItemLayoutResource) {
- super(context, 0);
- this.adsItemLayoutResource = adsItemLayoutResource;
- }
-
- public void setData(List<AdsEntry> data) {
- clear();
- if (data != null) {
- addAll(data);
- }
- }
-
- /**
- * Populate new items in the list.
- */
- @Override
- public View getView(final int position, final View convertView, final ViewGroup parent) {
-
- // We need to get the best view (re-used if possible) and then
- // retrieve its corresponding ViewHolder, which optimizes lookup efficiency
- final View view = getWorkingView(convertView);
- final ViewHolder viewHolder = getViewHolder(view);
- final AdsEntry entry = getItem(position);
-
- // Setting the text view
- viewHolder.titleView.setText(entry.getTitle());
-
- viewHolder.textView.setText(entry.getText());
-
- // Setting image view
- viewHolder.imageView.setImageBitmap(entry.getIcon());
-
-
- return view;
- }
-
- private View getWorkingView(final View convertView) {
- // The workingView is basically just the convertView re-used if possible
- // or inflated new if not possible
- View workingView = null;
-
- if(null == convertView) {
- final Context context = getContext();
- final LayoutInflater inflater = (LayoutInflater)context.getSystemService
- (Context.LAYOUT_INFLATER_SERVICE);
-
- workingView = inflater.inflate(adsItemLayoutResource, null);
- } else {
- workingView = convertView;
- }
-
- return workingView;
- }
-
- private ViewHolder getViewHolder(final View workingView) {
- // The viewHolder allows us to avoid re-looking up view references
- // Since views are recycled, these references will never change
- final Object tag = workingView.getTag();
- ViewHolder viewHolder = null;
-
-
- if(null == tag || !(tag instanceof ViewHolder)) {
- viewHolder = new ViewHolder();
-
- viewHolder.titleView = (TextView) workingView.findViewById(R.id.ads_entry_title);
- viewHolder.textView = (TextView) workingView.findViewById(R.id.ads_entry_text);
- viewHolder.imageView = (ImageView) workingView.findViewById(R.id.ads_entry_icon);
-
- workingView.setTag(viewHolder);
-
- } else {
- viewHolder = (ViewHolder) tag;
- }
-
- return viewHolder;
- }
-
- /**
- * ViewHolder allows us to avoid re-looking up view references
- * Since views are recycled, these references will never change
- */
- private static class ViewHolder {
- public TextView titleView;
- public TextView textView;
- public ImageView imageView;
- }
- }
-
- /**
- * Encapsulates information about an ads entry
- */
- public static class AdsEntry {
-
- private final String title;
- private final String text;
- private final Bitmap icon;
- private final int idAd;
- private final String URL;
-
- public AdsEntry(final String title, final String text, final Bitmap icon, final int idAd, final String URL) {
- this.title = title;
- this.text = text;
- this.icon = icon;
- this.idAd = idAd;
- this.URL = URL;
- }
-
- /**
- * @return Title of ads entry
- */
- public String getTitle() {
- return title;
- }
-
- /**
- * @return Text of ads entry
- */
- public String getText() {
- return text;
- }
-
- /**
- * @return Icon of this ads entry
- */
- public Bitmap getIcon() {
- return icon;
- }
-
- /**
- * @return Ad unique identifier of this ads entry
- */
- public int getIdAd() {
- return idAd;
- }
-
- /**
- * @return URL matching this ad.
- */
- public String getURL() {
- return URL;
- }
- }
-
- /**
- * A custom Loader that loads all of the installed applications.
- */
- public static class AdsListLoader extends AsyncTaskLoader<List<AdsEntry>> {
- private static final String TAG = "AdsListLoader";
- List<AdsEntry> mApps;
-
- public AdsListLoader(Context context) {
- super(context);
- }
-
- /**
- * This is where the bulk of our work is done. This function is
- * called in a background thread and should generate a new set of
- * data to be published by the loader.
- */
- @Override
- public List<AdsEntry> loadInBackground() {
- // Create corresponding array of entries and load their labels.
- List<AdsEntry> entries = getAdsEntries();
-
- return entries;
- }
-
- private List<AdsEntry> getAdsEntries() {
- final List<AdsEntry> entries = new ArrayList<AdsEntry>();
- final Uri uri = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer");
- final ContentValues values = new ContentValues();
-
- Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null);
- try {
- if (cursor.moveToFirst()) {
- do {
- values.clear();
- Bitmap bitMap = null;
- FileInputStream file = null;
- try {
- file = getContext().openFileInput(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_PATH)));
- bitMap = BitmapFactory.decodeStream(file);
- } catch (FileNotFoundException e) {
- //Giving more chances to other ads
- continue;
- } catch (IllegalArgumentException e) {
- //Giving more chances to other ads
- continue;
- }
- finally {
- if (file != null) {
- try {
- file.close();
- } catch (IOException e) {
- Log.w(TAG, "Error while closing image file.");
- }
- }
- }
- entries.add(new AdsEntry(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_AD_NAME)),
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_TEXT)), bitMap,
- cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_ID_AD)),
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_URL))));
- if (cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_IS_READ)) == 0)
- {
- values.put(Indexer.Index.COLUMN_NAME_IS_READ, new Integer(1));
- Uri uriUpdate = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer/" +
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index._ID)));
- getContext().getContentResolver().update(uriUpdate, values, null, null);
- }
- }while (cursor.moveToNext());
- }
- }finally {
- cursor.close();
- }
-
- return entries;
- }
-
- /**
- * Called when there is new data to deliver to the client. The
- * super class will take care of delivering it; the implementation
- * here just adds a little more logic.
- */
- @Override
- public void deliverResult(List<AdsEntry> apps) {
- mApps = apps;
-
- if (isStarted()) {
- // If the Loader is currently started, we can immediately
- // deliver its results.
- super.deliverResult(apps);
- }
- }
-
- /**
- * Handles a request to start the Loader.
- */
- @Override
- protected void onStartLoading() {
- if (mApps != null) {
- // If we currently have a result available, deliver it
- // immediately.
- deliverResult(mApps);
- }
-
- if (takeContentChanged() || mApps == null) {
- // If the data has changed since the last time it was loaded
- // or is not currently available, start a load.
- forceLoad();
- }
- }
-
- /**
- * Handles a request to cancel a load.
- */
- @Override
- public void onCanceled(List<AdsEntry> apps) {
- super.onCanceled(apps);
-
- // At this point we can release the resources associated with 'apps'
- // if needed.
- }
-
- /**
- * Handles a request to completely reset the Loader.
- */
- @Override
- protected void onReset() {
- super.onReset();
-
- // Ensure the loader is stopped
- onStopLoading();
-
- // At this point we can release the resources associated with 'apps'
- // if needed.
- if (mApps != null) {
- mApps = null;
- }
- }
- }
-}
import java.util.List;
import de.android.mobiads.MobiAdsService;
import de.android.mobiads.R;
-import de.android.mobiads.list.MobiAdsLatest.AdsEntry;
-import de.android.mobiads.list.MobiAdsLatest.AdsEntryAdapter;
-import de.android.mobiads.list.MobiAdsLatest.AdsListLoader;
+import de.android.mobiads.list.MobiAdsList.AdsEntry;
+import de.android.mobiads.list.MobiAdsList.AdsEntryAdapter;
+import de.android.mobiads.list.MobiAdsList.AdsListLoader;
import android.app.ActivityManager;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
-public class MobiAdsLatestList extends ListActivity implements LoaderManager.LoaderCallbacks<List<AdsEntry>> {
+public class MobiAdsLatestList extends ListActivity implements LoaderManager.LoaderCallbacks<List<AdsEntry>>
+{
AdsEntryAdapter mAdapter;
@Override
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
+import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
+import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import de.android.mobiads.provider.Indexer;
public class MobiAdsList extends Activity {
- Menu mMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
this.startActivity(intent);
return true;
case R.id.menuads_login:
- intent = new Intent("android.intent.action.MOBIADS").
- setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.MobiAdsLoginActivity"));
- this.startActivity(intent);
+ if (Cookie.getCookie() != null) {
+ createAlertDialog(R.string.alert_dialog_logged);
+ }
+ else {
+ intent = new Intent("android.intent.action.MOBIADS").
+ setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.MobiAdsLoginActivity"));
+ this.startActivity(intent);
+ }
return true;
default:
return false;
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
- super.onPrepareOptionsMenu(menu);
- MenuItem item = menu.findItem(R.id.menuads_settings);
- item.getIcon().setAlpha(70);
- mMenu = menu;
- return true;
+ return super.onPrepareOptionsMenu(menu);
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
}
-
- //Si doy al boton pa tras pasa por onCreateOptionsMenu y onPrepareOptionsMenu
- //Si doy al boton home solo pasa por onResume
- //:/
- @Override
- protected void onResume() {
- super.onResume();
-
-// if (Cookie.getCookie() != null) {
-// MenuItem item = mMenu.findItem(R.id.menuads_settings);
-// item.getIcon().setAlpha(255);
-// item = mMenu.findItem(R.id.menuads_settings);
-// item.setEnabled(true);
-// item = mMenu.findItem(R.id.menuads_login);
-// item.setEnabled(false);
-// item.setVisible(false);
-// }
- }
/**
public static class MobiAdsListFragment extends ListFragment implements OnQueryTextListener,
LoaderManager.LoaderCallbacks<List<AdsEntry>> {
+ private static final String TAG = "MobiAdsListFragment";
AdsEntryAdapter mAdapter;
// If non-null, this is the current filter the user has provided.
String mCurFilter;
+ AsyncTask<Void, Void, Void> mOnItemClick;
@Override
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
+
+
+ mOnItemClick = new AsyncTask<Void, Void, Void>() {
+
+ @Override
+ protected Void doInBackground(Void... params) {
+ final Uri uri = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer");
+ final ContentValues values = new ContentValues();
+ Cursor cursor = null;
+ try {
+ cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
+ values.put(Indexer.Index.COLUMN_NAME_IS_READ, new Integer(1));
+ Uri uriUpdate = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer/" +
+ cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index._ID)));
+
+ getActivity().getContentResolver().update(uriUpdate, values, null, null);
+ }
+ catch(Throwable e) {
+ Log.e(TAG, "AsyncTask error");
+ }
+ finally {
+ if (cursor != null) {
+ cursor.close();
+ }
+ }
+
+ //Send BroadCast
+
+ return null;
+ }
+
+ };
}
//TODO: Broadcast receiver from service, and stop using onResume... :/
return URL;
}
}
+
+ private void createAlertDialog(int title) {
+ DialogFragment newFragment = AlertDialogFragment.newInstance(title);
+ newFragment.show(getFragmentManager(), "alertDialog");
+ }
+
+ //Create a helper for this or at least write its own file.
+ public static class AlertDialogFragment extends DialogFragment {
+
+ public static AlertDialogFragment newInstance(int title) {
+ AlertDialogFragment frag = new AlertDialogFragment();
+ Bundle args = new Bundle();
+
+ args.putInt("title", title);
+ frag.setArguments(args);
+
+ return frag;
+ }
+
+ @Override
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ int title = getArguments().getInt("title");
+
+ return new AlertDialog.Builder(getActivity())
+ .setIcon(android.R.drawable.ic_dialog_alert)
+ .setTitle(title)
+ .setPositiveButton(R.string.button_ok,
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+
+ }
+ }
+ )
+ .create();
+ }
+ }
}
+++ /dev/null
-package de.android.mobiads.list;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import de.android.mobiads.MobiAdsService;
-import de.android.mobiads.R;
-import de.android.mobiads.provider.Indexer;
-import android.app.Activity;
-import android.app.ActivityManager;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.Intent;
-import android.database.Cursor;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.net.Uri;
-import android.util.Log;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.ListView;
-import android.widget.AdapterView.OnItemClickListener;
-
-public class MobiAdsNewAdsActivity extends Activity {
- private static final String TAG = "MobiAdsNewAdsActivity";
-
- @Override
- public void onResume() {
- super.onResume();
- setContentView(R.layout.latest_ads);
-
- // Setup the list view
- final ListView newsEntryListView = (ListView) findViewById(R.id.list_frag);
- final AdsEntryAdapter newsEntryAdapter = new AdsEntryAdapter(this, R.layout.ads_entry_list_item);
- newsEntryListView.setAdapter(newsEntryAdapter);
-
- // Populate the list, through the adapter. Should I populate the whole list right now? I do not think so...
- // Find out a way to populate this list just when it is required... :/
- for(final AdsEntry entry : getAdsEntries()) {
- newsEntryAdapter.add(entry);
- }
-
- newsEntryListView.setOnItemClickListener(new OnItemClickListener() {
-
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- Uri uri = Uri.parse(newsEntryAdapter.getItem(position).getTitle());
- startActivity(new Intent(Intent.ACTION_VIEW, uri));
- }
- });
-
- }
-
- private List<AdsEntry> getAdsEntries() {
- final List<AdsEntry> entries = new ArrayList<AdsEntry>();
- final Uri uri = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" + "/isRead/");
- final ContentValues values = new ContentValues();
-
- Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
- try {
- if (cursor.moveToFirst()) {
- do {
- values.clear();
- Bitmap bitMap = null;
- FileInputStream file = null;
-
- try {
- file = this.openFileInput(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_PATH)));
- bitMap = BitmapFactory.decodeStream(file);
- } catch (FileNotFoundException e) {
- //Giving more chances to other ads
- continue;
- } catch (IllegalArgumentException e) {
- //Giving more chances to other ads
- continue;
- }
- finally {
- if (file != null) {
- try {
- file.close();
- } catch (IOException e) {
- Log.w(TAG, "Error while closing image file.");
- }
- }
- }
- entries.add(new AdsEntry(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_AD_NAME)),
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_TEXT)), bitMap,
- cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_ID_AD)),
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_URL))));
-
-
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_PATH));
- values.put(Indexer.Index.COLUMN_NAME_IS_READ, new Integer(1));
- Uri uriUpdate = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer/" +
- cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index._ID)));
- getContentResolver().update(uriUpdate, values, null, null);
- }while (cursor.moveToNext());
- }
- }finally {
- cursor.close();
- }
-
- if (this.isMyServiceRunning()) {
- showNotification(0, 0, getText(R.string.remote_service_content_empty_notification));
- }
-
- return entries;
- }
-
- private boolean isMyServiceRunning() {
- ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if (MobiAdsService.class.getName().equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
-
- public void showNotification(final int level, final int noReadAds, CharSequence contentText) {
- NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
-
- // Set the icon, scrolling text and timestamp
- Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext()).
- setSmallIcon(R.drawable.wheelnotification, level).
- setTicker(getText(R.string.remote_service_started_notification)).
- setWhen(System.currentTimeMillis()).
- setContentText(contentText).
- setContentTitle(getText(R.string.remote_service_title_notification)).
- setNumber(noReadAds);
- Notification notification = notificationBuilder.getNotification();
- notification.flags |= Notification.FLAG_NO_CLEAR;
-
- // Send the notification.
- // We use a string id because it is a unique number. We use it later to cancel.
- notificationManager.notify(R.string.remote_service_title_notification, notification);
- }
-}