一開始程式資料庫有無內容,若無則喚起一個Service在背景新增一百筆資料至資料庫,再新增資料的期間,Notification要能夠顯示目前的進度。而新增完後,Service要能夠讓Activity知道新增資料作業已經完成,並顯示出來。
AddMessage.java code:
package com.android.homework; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; public class AddMessage extends Activity { private SimpleAdapter myListAdapter; private ListView list; public static final int EDITMENU = 0; public static final int REMOVEMENU = 1; public static final int ADDMENU = 2; public static final int ADD_DIALOG_ID = 3; public static final int EDIT_DIALOG_ID = 4; public static final int DIALOG_SHOW = 5; public static final int DIALOG_DISMISS = 6; private int myYear; private int myMonth; private int myDay; private Button dateButton; private EditText nameText, ageText; private ArrayList<HashMap<String, String>> myList; public static final String BROADCAST = "com.android.homework.listview"; private MyBroadcast myBroadcast = new MyBroadcast(); private ProgressDialog dialog; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myListViewInit(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BROADCAST); this.registerReceiver(myBroadcast, intentFilter); if (!queryData()) { initDialog(); // start service Intent intent = new Intent(this, MyService.class); AddMessage.this.startService(intent); mhandler.sendEmptyMessage(DIALOG_SHOW); } else { loadData(); } } // initialize the progressDialog public void initDialog() { dialog = new ProgressDialog(this); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle(R.string.loading); dialog.setMessage(getString(R.string.wait)); dialog.setIcon(R.drawable.circle); dialog.setCancelable(true); } // handle the message for progressDialog private Handler mhandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case DIALOG_SHOW: dialog.show(); break; case DIALOG_DISMISS: dialog.dismiss(); Log.e("dialog cancel", "dialog dismiss here"); break; default: break; } super.handleMessage(msg); } }; // receive the broadcast from the MyService public class MyBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String strName = intent.getStringExtra("name"); String strAge = intent.getStringExtra("age"); String strYear = intent.getStringExtra("birthday"); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", getString(R.string.name) + strName); map.put("age", getString(R.string.age) + strAge); map.put("birthday", getString(R.string.birthday) + strYear); myList.add(map); myListAdapter.notifyDataSetChanged(); list.setSelection(list.getCount() - 1); int length = Integer.parseInt(strName); if (length == 100) { mhandler.sendEmptyMessage(DIALOG_DISMISS); } setOnClickListener(); } } public void myListViewInit() { list = (ListView) findViewById(R.id.ListView); myList = new ArrayList<HashMap<String, String>>(); myListAdapter = new SimpleAdapter(this, myList, R.layout.listview, new String[] { "name", "age", "birthday" }, new int[] { R.id.name, R.id.age, R.id.birthdaytext }); list.setAdapter(myListAdapter); } // query the database private boolean queryData() { Cursor c = this.getContentResolver().query(AddMessageContentProvider.CONTENT_URI, null, null, null, null); int count = c.getCount(); c.close(); switch (count) { case 0: return false; default: return true; } } // load the data from the database if it have data public void loadData() { Cursor c = this.getContentResolver().query(AddMessageContentProvider.CONTENT_URI, null, null, null, null); if (c.moveToFirst()) { do { String strName = c.getString(c.getColumnIndex("name")); String strAge = c.getString(c.getColumnIndex("age")); String strYear = c.getString(c.getColumnIndex("birthday")); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", getString(R.string.name) + strName); map.put("age", getString(R.string.age) + strAge); map.put("birthday", getString(R.string.birthday) + strYear); myList.add(map); myListAdapter.notifyDataSetChanged(); setOnClickListener(); } while (c.moveToNext()); c.close(); } } public void setOnClickListener() { this.registerForContextMenu(list); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { AddMessage.this.openContextMenu(arg1); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, EDITMENU, 0, "Edit"); menu.add(0, REMOVEMENU, 1, "Remove"); } public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, ADDMENU, 0, "Add"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { addmessage(ADD_DIALOG_ID); return super.onOptionsItemSelected(item); } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case EDITMENU: AdapterContextMenuInfo infoEdit = (AdapterContextMenuInfo) item.getMenuInfo(); editmessage(EDIT_DIALOG_ID, infoEdit); break; case REMOVEMENU: AdapterContextMenuInfo infoRemove = (AdapterContextMenuInfo) item.getMenuInfo(); myListViewRemove(infoRemove); break; default: break; } return super.onContextItemSelected(item); } public void addmessage(int id) { LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.dialog1, (ViewGroup) findViewById(R.id.dialog)); dateButton = (Button) layout.findViewById(R.id.birthdaybutton); nameText = (EditText) layout.findViewById(R.id.name); ageText = (EditText) layout.findViewById(R.id.age); dateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { datePickerChange(v); } }); new AlertDialog.Builder(this).setView(layout) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { myListViewAdd(nameText.getText().toString(), ageText.getText().toString(), dateButton.getText().toString()); } }).setNegativeButton("Cancel", null).show(); } protected void datePickerChange(View v) { new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { myYear = year; myMonth = monthOfYear; myDay = dayOfMonth; dateButton.setText(new StringBuilder().append(myYear).append("/") .append(myMonth + 1).append("/").append(myDay)); } }, 1986, 8, 30).show(); } private void editmessage(int id, final AdapterContextMenuInfo info) { LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.dialog1, (ViewGroup) findViewById(R.id.dialog)); dateButton = (Button) layout.findViewById(R.id.birthdaybutton); nameText = (EditText) layout.findViewById(R.id.name); ageText = (EditText) layout.findViewById(R.id.age); final String nameBefore = myList.get(info.position).get("name").substring(5); String ageBefore = myList.get(info.position).get("age").substring(4); nameText.setText(nameBefore); ageText.setText(ageBefore); dateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { datePickerChange(v); } }); new AlertDialog.Builder(this).setView(layout) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { HashMap<String, String> map = new HashMap<String, String>(); map.put("name", getString(R.string.name) + nameText.getText()); map.put("age", getString(R.string.age) + ageText.getText()); map.put("birthday", getString(R.string.birthday) + dateButton.getText()); ContentResolver myContentResolver = getContentResolver(); ContentValues values = new ContentValues(); values.put(AddMessageContentProvider.NAME, nameText.getText().toString()); values.put(AddMessageContentProvider.AGE, ageText.getText().toString()); values.put(AddMessageContentProvider.BIRTHDAY, dateButton.getText() .toString()); String[] str = { nameBefore }; myContentResolver.update(AddMessageContentProvider.CONTENT_URI, values, null, str); myList.set(info.position, map); myListAdapter.notifyDataSetChanged(); } }).setNegativeButton("Cancel", null).show(); } protected void myListViewAdd(String name, String age, String birthday) { ContentResolver myContentResolver = getContentResolver(); ContentValues values = new ContentValues(); values.put(AddMessageContentProvider.NAME, name); values.put(AddMessageContentProvider.AGE, age); values.put(AddMessageContentProvider.BIRTHDAY, birthday); myContentResolver.insert(AddMessageContentProvider.CONTENT_URI, values); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", getString(R.string.name) + name); map.put("age", getString(R.string.age) + age); map.put("birthday", getString(R.string.birthday) + birthday); myList.add(map); myListAdapter.notifyDataSetChanged(); } // remove the list you choose protected void myListViewRemove(AdapterContextMenuInfo infoRemove) { myListAdapter.notifyDataSetChanged(); String str = myList.get(infoRemove.position).get("name").substring(5); ContentResolver myContentResolver = getContentResolver(); myContentResolver.delete(AddMessageContentProvider.CONTENT_URI, str, null); myList.remove(infoRemove.position); } @Override protected void onStop() { this.unregisterReceiver(myBroadcast); super.onStop(); } }
Myservice.java code:
package com.android.homework; import java.util.Random; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.widget.RemoteViews; public class MyService extends Service { private int index = 0; private int randomAge; private int year; private static final int NOTIFICATION_ID = 34234234; private NotificationManager mNotificationManager; private Notification notification; public static final String BROADCAST = "com.android.homework.listview"; private static final int ADD = 1; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub switch (msg.what) { case ADD: index++; if (index < 100) { myWritedata(); notification.contentView .setProgressBar(R.id.progressbar, 100, index, false); notification.contentView.setTextViewText(R.id.textview, index + "/100"); mNotificationManager.notify(NOTIFICATION_ID, notification); mHandler.sendEmptyMessageDelayed(ADD, 200); } else if (index == 100) { notification.contentView .setProgressBar(R.id.progressbar, 100, index, false); notification.contentView.setTextViewText(R.id.textview, index + "/100"); mNotificationManager.notify(NOTIFICATION_ID, notification); myWritedata(); mNotificationManager.cancel(NOTIFICATION_ID); } break; default: break; } super.handleMessage(msg); } }; @Override public void onCreate() { // TODO Auto-generated method stub notificationInit(); mHandler.sendEmptyMessage(ADD); super.onCreate(); } // send the broadcast with a intent which contains the message for listView public void mySendBroadcast(String name, String age, String birthday) { Intent intent = new Intent(BROADCAST); intent.putExtra("name", name); intent.putExtra("age", age); intent.putExtra("birthday", birthday); sendBroadcast(intent); } public void notificationInit() { String ns = Context.NOTIFICATION_SERVICE; Context context = getApplicationContext(); mNotificationManager = (NotificationManager) getSystemService(ns); // CharSequence tickerText = "establishing database"; notification = new Notification(R.drawable.smile, getString(R.string.ticker), System.currentTimeMillis()); Intent notificationIntent = new Intent(this, AddMessage.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, "notification_peter", "write database", contentIntent); final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification); contentView.setImageViewResource(R.id.imageview, R.drawable.smile); contentView.setTextViewText(R.id.textview, index + "/100"); notification.contentView = contentView; notification.contentView.setProgressBar(R.id.progressbar, 100, index, false); mNotificationManager.notify(NOTIFICATION_ID, notification); } // write data to the database and send broadcast at the same time public void myWritedata() { Random random = new Random(); randomAge = random.nextInt(53) + 18; year = 2011 - randomAge; String myYear = year + "/08/30"; ContentResolver myContentResolver = getContentResolver(); ContentValues values = new ContentValues(); values.put(AddMessageContentProvider.NAME, index); values.put(AddMessageContentProvider.AGE, randomAge); values.put(AddMessageContentProvider.BIRTHDAY, myYear); myContentResolver.insert(AddMessageContentProvider.CONTENT_URI, values); mySendBroadcast(String.valueOf(index), String.valueOf(randomAge), myYear); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } }
AddMessageContentProvider: this code is for database
package com.android.homework; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class AddMessageContentProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri .parse("content://com.android.homework.addmessagecontentprovider/personalInfoTable"); private static final String DB_NAME = "info.db"; private static final String TBL_NAME = "personalInfoTable"; private static final int DATABASE_VERSION = 2; public static final String NAME = "name"; public static final String AGE = "age"; public static final String BIRTHDAY = "birthday"; private DatabaseHelper mOpenHelper; private static final String CREATE_TBL = " create table " + TBL_NAME + " ( name text, age text, birthday text);"; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DB_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TBL); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "drop table " + TBL_NAME; db.execSQL(sql); onCreate(db); } } @Override public boolean onCreate() { mOpenHelper = new DatabaseHelper(getContext()); return true; } @Override public int delete(Uri uri, String arg1, String[] arg2) { // TODO Auto-generated method stub SQLiteDatabase db = mOpenHelper.getWritableDatabase(); return db.delete(TBL_NAME, "name='" + arg1 + "'", null); } @Override public String getType(Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri uri, ContentValues initialValues) { // TODO Auto-generated method stub ContentValues values = initialValues; SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(TBL_NAME, null, values); if (rowId > 0) { Uri myUri = ContentUris.withAppendedId(CONTENT_URI, rowId); return myUri; } throw new SQLException("Failed to insert row into " + uri); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); SQLiteDatabase db = mOpenHelper.getReadableDatabase(); qb.setTables(TBL_NAME); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, null); return c; } @Override public int update(Uri uri, ContentValues values, String where, String[] strName) { // TODO Auto-generated method stub SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // String rowId = uri.getPathSegments().get(1); return db.update(TBL_NAME, values, "name='" + strName[0] + "'", null); } }
notification.xml:
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/notification" android:padding="10dp" android:background="#880490FF" > <ImageView android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ProgressBar android:id="@+id/progressbar" android:layout_width="180dip" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" android:layout_gravity="center_vertical" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16px" android:textColor="#FF0000" /> </LinearLayout> </LinearLayout>
androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.homework" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/smile" android:label="@string/app_name"> <activity android:name=".AddMessage" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name=".AddMessageContentProvider" android:authorities="com.android.homework.addmessagecontentprovider" > </provider> <service android:name=".MyService"/> </application> </manifest>
listview 的布局文件见前面的博文
希望网友指点程序中的问题,谢谢。