当前位置:  编程技术>移动开发
本页文章导读:
    ▪开机自启动三        开机自启动3 一个例子xml: 代码<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission><receiver android:name=".OlympicsReceiver" android:label="@string/app_name">     <intent-.........
    ▪ 关于联系人的批改[目前只是这几个想法],基于2.1        关于联系人的修改[目前只是这几个想法],基于2.1 看了一些Android开源小应用的写法,感觉好像代码都比较乱,各种各样的都有虽然自己写的代码也很糟糕,但还是能感觉到在Android开发方.........
    ▪ getSharedPreferences(String name, int mode) of Service的兑现(转)       getSharedPreferences(String name, int mode) of Service的实现(转) I found a method getSharedPreferences(String name, int mode) in Service classthan I want to see how it implementsfirst I got a abstrat method in Context class/android_opensou.........

[1]开机自启动三
    来源: 互联网  发布时间: 2014-02-18
开机自启动3
一个例子
xml:
代码
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<receiver android:name=".OlympicsReceiver" android:label="@string/app_name">
    <intent-filter>
       <action android:name="android.intent.action.BOOT_COMPLETED" />
       <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</receiver>
java:
代码
public class OlympicsReceiver extends IntentReceiver
{
    /*要接收的intent源*/
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";
       
    public void onReceiveIntent(Context context, Intent intent)
    {
        if (intent.getAction().equals(ACTION))
        {
                  context.startService(new Intent(context,
                       OlympicsService.class), null);//启动倒计时服务
             Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
        }
    }
}

注意:现在的IntentReceiver已经变为BroadcastReceiver,OnReceiveIntent为onReceive。所以java这边的代码为:
(也可以实现应用程序开机自动启动)
Code
public class OlympicsReceiver extends BroadcastReceiver
{
    /*要接收的intent源*/
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";
       
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().equals(ACTION))
        {
                  context.startService(new Intent(context,
                       OlympicsService.class), null);//启动倒计时服务
             Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
            //这边可以添加开机自动启动的应用程序代码
        }
    }
}

    
[2] 关于联系人的批改[目前只是这几个想法],基于2.1
    来源: 互联网  发布时间: 2014-02-18
关于联系人的修改[目前只是这几个想法],基于2.1
看了一些Android开源小应用的写法,感觉好像代码都比较乱,各种各样的都有
虽然自己写的代码也很糟糕,但还是能感觉到在Android开发方面的代码比JEE的要乱很多
着重点不一样吧

联系人修改
1、根据已有的数据,特别是id,查询出要修改哪几条数据,然后一条条去修改
这是一种方法,但我目前没有采取这种方法,因为服务器端返回的数据中只包含了一些数据,没有很多像主键这样的东西,所以我采取了另外一种写法

2、删除data表中有关的数据,然后再新增,这是我目前采用的方法,raw_contacts表和contacts表数据不删除,只是修改
基本代码类似下面

				// 已知一个ID了,要修改他下面的数据
				// 删除他下面的DATA数据,然后再新增数据
				long id = 3l;
				// 根据id查询出rawid
				// 可能有多个rawid
				Cursor cursor = rawContactsCursor(getApplicationContext(), id);
				while (cursor.moveToNext()) {
					long rawid = cursor.getLong(cursor
							.getColumnIndex(RawContacts._ID));
					ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

					ops.add(ContentProviderOperation
							.newDelete(Data.CONTENT_URI).withSelection(
									Data.RAW_CONTACT_ID + "=?",
									new String[] { String.valueOf(rawid) })
							.build());
					ops.add(ContentProviderOperation
							.newInsert(Data.CONTENT_URI).withValue(
									Data.RAW_CONTACT_ID, rawid).withValues(
									getNameNewCV()).build());

					ops.add(ContentProviderOperation
							.newInsert(Data.CONTENT_URI).withValue(
									Data.RAW_CONTACT_ID, rawid).withValues(
									getPhoneNewCV()).build());
					try {
						ContentProviderResult[] rst = getContentResolver()
								.applyBatch(ContactsContract.AUTHORITY, ops);
					} catch (RemoteException e) {
						e.printStackTrace();
					} catch (OperationApplicationException e) {
						e.printStackTrace();
					}
				}

	private Cursor rawContactsCursor(Context ctx, long id) {
		return ctx.getContentResolver().query(
				ContactsContract.RawContacts.CONTENT_URI, null,
				ContactsContract.RawContacts.CONTACT_ID + "=?",
				new String[] { String.valueOf(id) }, null);
	}

	public ContentValues getNameNewCV() {
		ContentValues cv = new ContentValues();
		cv.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
		cv.put(StructuredName.DISPLAY_NAME, "武 体");
		cv.put(StructuredName.GIVEN_NAME, "体");
		cv.put(StructuredName.FAMILY_NAME, "武");
		return cv;
	}

	public ContentValues getPhoneNewCV() {
		ContentValues cv = new ContentValues();
		cv.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		cv.put(Phone.NUMBER, "666666");
		cv.put(Phone.TYPE, Phone.TYPE_COMPANY_MAIN);
		return cv;
	}


备注:这样修改还是有问题的,貌似contacts会生成新的记录,这样对于需要contact_id的情况就是悲剧啊

下面删除联系人的代码也还是有问题的
				// 删除联系人
				// 删除Data
				long id = 1l;
				// 根据id查询出rawid
				// 可能有多个rawid
				Cursor cursor = rawContactsCursor(getApplicationContext(), id);

				ArrayList<ContentProviderOperation> ops = null;
				while (cursor.moveToNext()) {
					long rawid = cursor.getLong(cursor
							.getColumnIndex(RawContacts._ID));
					ops = new ArrayList<ContentProviderOperation>();
					ops.add(ContentProviderOperation
							.newDelete(Data.CONTENT_URI).withSelection(
									Data.RAW_CONTACT_ID + "=?",
									new String[] { String.valueOf(rawid) })
							.build());
					ops.add(ContentProviderOperation.newDelete(
							ContentUris.withAppendedId(RawContacts.CONTENT_URI,
									rawid)).build());

					ops.add(ContentProviderOperation.newDelete(
							ContentUris
									.withAppendedId(Contacts.CONTENT_URI, id))
							.build());

					try {
						ContentProviderResult[] rst = getContentResolver()
								.applyBatch(ContactsContract.AUTHORITY, ops);
					} catch (RemoteException e) {
						e.printStackTrace();
					} catch (OperationApplicationException e) {
						e.printStackTrace();
					}
				}

    
[3] getSharedPreferences(String name, int mode) of Service的兑现(转)
    来源: 互联网  发布时间: 2014-02-18
getSharedPreferences(String name, int mode) of Service的实现(转)
I found a method getSharedPreferences(String name, int mode) in Service class

than I want to see how it implements

first I got a abstrat method in Context class

/android_opensource/frameworks/base/core/java/android/content/Context.java
...
262     /**
263      * Retrieve and hold the contents of the preferences file 'name', returning
264      * a SharedPreferences through which you can retrieve and modify its
265      * values.  Only one instance of the SharedPreferences object is returned
266      * to any callers for the same name, meaning they will see each other's
267      * edits as soon as they are made.
268      *
269      * @param name Desired preferences file. If a preferences file by this name
270      * does not exist, it will be created when you retrieve an
271      * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
272      * @param mode Operating mode.  Use 0 or {@link #MODE_PRIVATE} for the
273      * default operation, {@link #MODE_WORLD_READABLE}
274      * and {@link #MODE_WORLD_WRITEABLE} to control permissions.
275      *
276      * @return Returns the single SharedPreferences instance that can be used
277      *         to retrieve and modify the preference values.
278      *
279      * @see #MODE_PRIVATE
280      * @see #MODE_WORLD_READABLE
281      * @see #MODE_WORLD_WRITEABLE
282      */
283     public abstract SharedPreferences getSharedPreferences(String name,
284             int mode);
...


and Service extends ContextWrapper, ContextWrapper extends Context just implements from a new Context instance
/android_opensource/frameworks/base/core/java/android/content/ContextWrapper.java
...
132     @Override
133     public SharedPreferences getSharedPreferences(String name, int mode) {
134         return mBase.getSharedPreferences(name, mode);
135     }
...


so where does it pass the Context instance to the Service

The Context instance must implements the method

than I found the implementation in ApplicationContext which extends the Context

android_opensource/frameworks/base/core/java/android/app/ApplicationContext.java
...
@Override
303     public SharedPreferences getSharedPreferences(String name, int mode) {
304         SharedPreferencesImpl sp;
305         File f = makeFilename(getPreferencesDir(), name + ".xml");
306         synchronized (sSharedPrefs) {
307             sp = sSharedPrefs.get(f);
308             if (sp != null && !sp.hasFileChanged()) {
309                 //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);
310                 return sp;
311             }
312         }
313
314         FileInputStream str = null;
315         File backup = makeBackupFile(f);
316         if (backup.exists()) {
317             f.delete();
318             backup.renameTo(f);
319         }
320
321         // Debugging
322         if (f.exists() && !f.canRead()) {
323             Log.w(TAG, "Attempt to read preferences file " + f + " without permission");
324         }
325
326         Map map = null;
327         if (f.exists() && f.canRead()) {
328             try {
329                 str = new FileInputStream(f);
330                 map = XmlUtils.readMapXml(str);
331                 str.close();
332             } catch (org.xmlpull.v1.XmlPullParserException e) {
333                 Log.w(TAG, "getSharedPreferences", e);
334             } catch (FileNotFoundException e) {
335                 Log.w(TAG, "getSharedPreferences", e);
336             } catch (IOException e) {
337                 Log.w(TAG, "getSharedPreferences", e);
338             }
339         }
340
341         synchronized (sSharedPrefs) {
342             if (sp != null) {
343                 //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);
344                 sp.replace(map);
345             } else {
346                 sp = sSharedPrefs.get(f);
347                 if (sp == null) {
348                     sp = new SharedPreferencesImpl(f, mode, map);
349                     sSharedPrefs.put(f, sp);
350                 }
351             }
352             return sp;
353         }
354     }
...


but I still did't found where it pass the ApplicationContext in

after few minutes search I found another class ActivityThread

It had a method handleCreateService which should be called when create a Service

android_opensource/frameworks/base/core/java/android/app/ActivityThread.java
...
2436     private final void handleCreateService(CreateServiceData data) {
2437         // If we are getting ready to gc after going to the background, well
2438         // we are back active so skip it.
2439         unscheduleGcIdler();
2440
2441         PackageInfo packageInfo = getPackageInfoNoCheck(
2442                 data.info.applicationInfo);
2443         Service service = null;
2444         try {
2445             java.lang.ClassLoader cl = packageInfo.getClassLoader();
2446             service = (Service) cl.loadClass(data.info.name).newInstance();
2447         } catch (Exception e) {
2448             if (!mInstrumentation.onException(service, e)) {
2449                 throw new RuntimeException(
2450                     "Unable to instantiate service " + data.info.name
2451                     + ": " + e.toString(), e);
2452             }
2453         }
2454
2455         try {
2456             if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2457
2458             ApplicationContext context = new ApplicationContext();
2459             context.init(packageInfo, null, this);
2460
2461             Application app = packageInfo.makeApplication();
2462             context.setOuterContext(service);
2463             service.attach(context, this, data.info.name, data.token, app,
2464                     ActivityManagerNative.getDefault());
2465             service.onCreate();
2466             mServices.put(data.token, service);
2467             try {
2468                 ActivityManagerNative.getDefault().serviceDoneExecuting(data.token);
2469             } catch (RemoteException e) {
2470                 // nothing to do.
2471             }
2472         } catch (Exception e) {
2473             if (!mInstrumentation.onException(service, e)) {
2474                 throw new RuntimeException(
2475                     "Unable to create service " + data.info.name
2476                     + ": " + e.toString(), e);
2477             }
2478         }
2479     }
...


In the method it call the service's method attch and pass a ApplicationContext as parameter

then The service's attch method would pass the context throght the attachBaseContext(context) method
android_opensource/frameworks/base/core/java/android/app/Service.java
...
356     public final void attach(
357             Context context,
358             ActivityThread thread, String className, IBinder token,
359             Application application, Object activityManager) {
360         attachBaseContext(context);
361         mThread = thread;           // NOTE:  unused - remove?
362         mClassName = className;
363         mToken = token;
364         mApplication = application;
365         mActivityManager = (IActivityManager)activityManager;
366     }
...

android_opensource/frameworks/base/core/java/android/content/ContextWrapper.java
...
50     /**
51      * Set the base context for this ContextWrapper.  All calls will then be
52      * delegated to the base context.  Throws
53      * IllegalStateException if a base context has already been set.
54      *
55      * @param base The new base context for this wrapper.
56      */
57     protected void attachBaseContext(Context base) {
58         if (mBase != null) {
59             throw new IllegalStateException("Base context already set");
60         }
61         mBase = base;
62     }
...

so the service get the Context instance which implement the getSharedPreferences(String name, int mode) method

the original url http://hi.baidu.com/ksoftware/blog/item/de17bbd6806b202507088bd8.html

    
最新技术文章:
▪Android开发之登录验证实例教程
▪Android开发之注册登录方法示例
▪Android获取手机SIM卡运营商信息的方法
▪Android实现将已发送的短信写入短信数据库的...
▪Android发送短信功能代码
▪Android根据电话号码获得联系人头像实例代码
▪Android中GPS定位的用法实例
▪Android实现退出时关闭所有Activity的方法
▪Android实现文件的分割和组装
▪Android录音应用实例教程
▪Android双击返回键退出程序的实现方法
▪Android实现侦听电池状态显示、电量及充电动...
▪Android获取当前已连接的wifi信号强度的方法
▪Android实现动态显示或隐藏密码输入框的内容
▪根据USER-AGENT判断手机类型并跳转到相应的app...
▪Android Touch事件分发过程详解
▪Android中实现为TextView添加多个可点击的文本
▪Android程序设计之AIDL实例详解
▪Android显式启动与隐式启动Activity的区别介绍
▪Android按钮单击事件的四种常用写法总结
▪Android消息处理机制Looper和Handler详解
▪Android实现Back功能代码片段总结
▪Android实用的代码片段 常用代码总结
▪Android实现弹出键盘的方法
▪Android中通过view方式获取当前Activity的屏幕截...
▪Android提高之自定义Menu(TabMenu)实现方法
docker中文入门学习手册 iis7站长之家
▪Android提高之MediaPlayer播放网络音频的实现方法...
▪Android提高之MediaPlayer播放网络视频的实现方法...
▪Android提高之手游转电视游戏的模拟操控
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3