Initial Contribution

This commit is contained in:
The Android Open Source Project
2008-10-21 07:00:00 -07:00
commit 5c11852110
2143 changed files with 253519 additions and 0 deletions

View File

@@ -0,0 +1,94 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceActivity;
import android.preference.CheckBoxPreference;
import android.widget.Toast;
/**
* Example that shows finding a preference from the hierarchy and a custom preference type.
*/
public class AdvancedPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String KEY_MY_PREFERENCE = "my_preference";
public static final String KEY_ADVANCED_CHECKBOX_PREFERENCE = "advanced_checkbox_preference";
private CheckBoxPreference mCheckBoxPreference;
private Handler mHandler = new Handler();
/**
* This is a simple example of controlling a preference from code.
*/
private Runnable mForceCheckBoxRunnable = new Runnable() {
public void run() {
if (mCheckBoxPreference != null) {
mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
}
// Force toggle again in a second
mHandler.postDelayed(this, 1000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the XML preferences file
addPreferencesFromResource(R.xml.advanced_preferences);
// Get a reference to the checkbox preference
mCheckBoxPreference = (CheckBoxPreference)getPreferenceScreen().findPreference(
KEY_ADVANCED_CHECKBOX_PREFERENCE);
}
@Override
protected void onResume() {
super.onResume();
// Start the force toggle
mForceCheckBoxRunnable.run();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
mHandler.removeCallbacks(mForceCheckBoxRunnable);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Let's do something when my counter preference value changes
if (key.equals(KEY_MY_PREFERENCE)) {
Toast.makeText(this, "Thanks! You increased my count to "
+ sharedPreferences.getInt(key, 0), Toast.LENGTH_SHORT).show();
}
}
}

View File

@@ -0,0 +1,168 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.util.Calendar;
/**
* Example of scheduling one-shot and repeating alarms. See
* {@link OneShotAlarm} for the code run when the one-shot alarm goes off, and
* {@link RepeatingAlarm} for the code run when the repeating alarm goes off.
* <h4>Demo</h4>
App/Service/Alarm Controller
<h4>Source files</h4>
<table class="LinkTable">
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/AlarmController.java</td>
<td class="DescrColumn">The activity that lets you schedule alarms</td>
</tr>
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/OneShotAlarm.java</td>
<td class="DescrColumn">This is an intent receiver that executes when the
one-shot alarm goes off</td>
</tr>
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/RepeatingAlarm.java</td>
<td class="DescrColumn">This is an intent receiver that executes when the
repeating alarm goes off</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/alarm_controller.xml</td>
<td class="DescrColumn">Defines contents of the screen</td>
</tr>
</table>
*/
public class AlarmController extends Activity {
Toast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_controller);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.one_shot);
button.setOnClickListener(mOneShotListener);
button = (Button)findViewById(R.id.start_repeating);
button.setOnClickListener(mStartRepeatingListener);
button = (Button)findViewById(R.id.stop_repeating);
button.setOnClickListener(mStopRepeatingListener);
}
private OnClickListener mOneShotListener = new OnClickListener() {
public void onClick(View v) {
// When the alarm goes off, we want to broadcast an Intent to our
// BroadcastReceiver. Here we make an Intent with an explicit class
// name to have our own receiver (which has been published in
// AndroidManifest.xml) instantiated and called, and then create an
// IntentSender to have the intent executed as a broadcast.
Intent intent = new Intent(AlarmController.this, OneShotAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
0, intent, 0);
// We want the alarm to go off 30 seconds from now.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 30);
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
// Tell the user about what we did.
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(AlarmController.this, R.string.one_shot_scheduled,
Toast.LENGTH_LONG);
mToast.show();
}
};
private OnClickListener mStartRepeatingListener = new OnClickListener() {
public void onClick(View v) {
// When the alarm goes off, we want to broadcast an Intent to our
// BroadcastReceiver. Here we make an Intent with an explicit class
// name to have our own receiver (which has been published in
// AndroidManifest.xml) instantiated and called, and then create an
// IntentSender to have the intent executed as a broadcast.
// Note that unlike above, this IntentSender is configured to
// allow itself to be sent multiple times.
Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
0, intent, 0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 15*1000;
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 15*1000, sender);
// Tell the user about what we did.
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(AlarmController.this, R.string.repeating_scheduled,
Toast.LENGTH_LONG);
mToast.show();
}
};
private OnClickListener mStopRepeatingListener = new OnClickListener() {
public void onClick(View v) {
// Create the same intent, and thus a matching IntentSender, for
// the one that was scheduled.
Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
0, intent, 0);
// And cancel the alarm.
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.cancel(sender);
// Tell the user about what we did.
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(AlarmController.this, R.string.repeating_unscheduled,
Toast.LENGTH_LONG);
mToast.show();
}
};
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* This demonstrates how you can schedule an alarm that causes a service to
* be started. This is useful when you want to schedule alarms that initiate
* long-running operations, such as retrieving recent e-mails.
*/
public class AlarmService extends Activity {
private PendingIntent mAlarmSender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an IntentSender that will launch our service, to be scheduled
// with the alarm manager.
mAlarmSender = PendingIntent.getService(AlarmService.this,
0, new Intent(AlarmService.this, AlarmService_Service.class), 0);
setContentView(R.layout.alarm_service);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.start_alarm);
button.setOnClickListener(mStartAlarmListener);
button = (Button)findViewById(R.id.stop_alarm);
button.setOnClickListener(mStopAlarmListener);
}
private OnClickListener mStartAlarmListener = new OnClickListener() {
public void onClick(View v) {
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 30*1000, mAlarmSender);
// Tell the user about what we did.
Toast.makeText(AlarmService.this, R.string.repeating_scheduled,
Toast.LENGTH_LONG).show();
}
};
private OnClickListener mStopAlarmListener = new OnClickListener() {
public void onClick(View v) {
// And cancel the alarm.
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.cancel(mAlarmSender);
// Tell the user about what we did.
Toast.makeText(AlarmService.this, R.string.repeating_unscheduled,
Toast.LENGTH_LONG).show();
}
};
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.Toast;
/**
* This is an example of implementing an application service that will run in
* response to an alarm, allowing us to move long duration work out of an
* intent receiver.
*
* @see AlarmService
* @see AlarmService_Alarm
*/
public class AlarmService_Service extends Service {
NotificationManager mNM;
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// show the icon in the status bar
showNotification();
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
Thread thr = new Thread(null, mTask, "AlarmService_Service");
thr.start();
}
@Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
mNM.cancel(R.string.alarm_service_started);
// Tell the user we stopped.
Toast.makeText(this, R.string.alarm_service_finished, Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
// Normally we would do some work here... for our sample, we will
// just sleep for 30 seconds.
long endTime = System.currentTimeMillis() + 15*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (mBinder) {
try {
mBinder.wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Done with our work... stop the service!
AlarmService_Service.this.stopSelf();
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.alarm_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmService.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.alarm_service_label),
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.alarm_service_started, notification);
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}

View File

@@ -0,0 +1,306 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.android.apis.R;
/**
* Example of how to use an {@link android.app.AlertDialog}.
* <h3>AlertDialogSamples</h3>
<p>This demonstrates the different ways the AlertDialog can be used.</p>
<h4>Demo</h4>
App/Dialog/Alert Dialog
<h4>Source files</h4>
* <table class="LinkTable">
* <tr>
* <td >src/com.example.android.apis/app/AlertDialogSamples.java</td>
* <td >The Alert Dialog Samples implementation</td>
* </tr>
* <tr>
* <td >/res/any/layout/alert_dialog.xml</td>
* <td >Defines contents of the screen</td>
* </tr>
* </table>
*/
public class AlertDialogSamples extends Activity {
private static final int DIALOG_YES_NO_MESSAGE = 1;
private static final int DIALOG_YES_NO_LONG_MESSAGE = 2;
private static final int DIALOG_LIST = 3;
private static final int DIALOG_PROGRESS = 4;
private static final int DIALOG_SINGLE_CHOICE = 5;
private static final int DIALOG_MULTIPLE_CHOICE = 6;
private static final int DIALOG_TEXT_ENTRY = 7;
private static final int MAX_PROGRESS = 100;
private ProgressDialog mProgressDialog;
private int mProgress;
private Handler mProgressHandler;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_YES_NO_MESSAGE:
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_two_buttons_title)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Cancel so do some stuff */
}
})
.create();
case DIALOG_YES_NO_LONG_MESSAGE:
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_two_buttons_msg)
.setMessage(R.string.alert_dialog_two_buttons2_msg)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.setNeutralButton(R.string.alert_dialog_something, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Something so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Cancel so do some stuff */
}
})
.create();
case DIALOG_LIST:
return new AlertDialog.Builder(AlertDialogSamples.this)
.setTitle(R.string.select_dialog)
.setItems(R.array.select_dialog_items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/* User clicked so do some stuff */
String[] items = getResources().getStringArray(R.array.select_dialog_items);
new AlertDialog.Builder(AlertDialogSamples.this)
.setMessage("You selected: " + which + " , " + items[which])
.show();
}
})
.create();
case DIALOG_PROGRESS:
mProgressDialog = new ProgressDialog(AlertDialogSamples.this);
mProgressDialog.setIcon(R.drawable.alert_dialog_icon);
mProgressDialog.setTitle(R.string.select_dialog);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMax(MAX_PROGRESS);
mProgressDialog.setButton(getText(R.string.alert_dialog_hide), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
}
});
mProgressDialog.setButton2(getText(R.string.alert_dialog_cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
});
return mProgressDialog;
case DIALOG_SINGLE_CHOICE:
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_single_choice)
.setSingleChoiceItems(R.array.select_dialog_items2, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked on a radio button do some stuff */
}
})
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
})
.create();
case DIALOG_MULTIPLE_CHOICE:
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.ic_popup_reminder)
.setTitle(R.string.alert_dialog_multi_choice)
.setMultiChoiceItems(R.array.select_dialog_items3,
new boolean[]{false, true, false, true, false, false, false},
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton,
boolean isChecked) {
/* User clicked on a check box do some stuff */
}
})
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
})
.create();
case DIALOG_TEXT_ENTRY:
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
}
return null;
}
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView(int)} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert_dialog);
/* Display a text message with yes/no buttons and handle each message as well as the cancel action */
Button twoButtonsTitle = (Button) findViewById(R.id.two_buttons);
twoButtonsTitle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_YES_NO_MESSAGE);
}
});
/* Display a long text message with yes/no buttons and handle each message as well as the cancel action */
Button twoButtons2Title = (Button) findViewById(R.id.two_buttons2);
twoButtons2Title.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_YES_NO_LONG_MESSAGE);
}
});
/* Display a list of items */
Button selectButton = (Button) findViewById(R.id.select_button);
selectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_LIST);
}
});
/* Display a custom progress bar */
Button progressButton = (Button) findViewById(R.id.progress_button);
progressButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_PROGRESS);
mProgress = 0;
mProgressDialog.setProgress(0);
mProgressHandler.sendEmptyMessage(0);
}
});
/* Display a radio button group */
Button radioButton = (Button) findViewById(R.id.radio_button);
radioButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_SINGLE_CHOICE);
}
});
/* Display a list of checkboxes */
Button checkBox = (Button) findViewById(R.id.checkbox_button);
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_MULTIPLE_CHOICE);
}
});
/* Display a text entry dialog */
Button textEntry = (Button) findViewById(R.id.text_entry_button);
textEntry.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_TEXT_ENTRY);
}
});
mProgressHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mProgress >= MAX_PROGRESS) {
mProgressDialog.dismiss();
} else {
mProgress++;
mProgressDialog.incrementProgressBy(1);
mProgressHandler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.os.RemoteException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.android.apis.R;
/**
* Front-end for launching {@link ContactsFilterInstrumentation} example
* instrumentation class.
*/
public class ContactsFilter extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_filter);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.go);
button.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener() {
public void onClick(View v) {
startInstrumentation(new ComponentName(ContactsFilter.this,
ContactsFilterInstrumentation.class), null, null);
}
};
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.view.KeyEvent;
import android.os.Bundle;
import android.util.Log;
import java.util.Map;
/**
* This is an example implementation of the {@link android.app.Instrumentation}
* class, allowing you to run tests against application code. The
* instrumentation implementation here is loaded into the application's
* process, for controlling and monitoring what it does.
*/
public class ContactsFilterInstrumentation extends Instrumentation {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments);
// When this instrumentation is created, we simply want to start
// its test code off in a separate thread, which will call back
// to us in onStart().
start();
}
@Override
public void onStart() {
super.onStart();
// First start the activity we are instrumenting -- the contacts
// list.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(getTargetContext(),
"com.android.phone.Dialer");
Activity activity = startActivitySync(intent);
// This is the Activity object that was started, to do with as we want.
Log.i("ContactsFilterInstrumentation", "Started: " + activity);
// We are going to enqueue a couple key events to simulate the user
// filtering the list. This is the low-level API so we must send both
// down and up events.
sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_M));
sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_M));
sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A));
sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_A));
// Wait for the activity to finish all of its processing.
waitForIdleSync();
// And we are done!
Log.i("ContactsFilterInstrumentation", "Done!");
finish(Activity.RESULT_OK, null);
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.view.KeyEvent;
import android.provider.Contacts;
import android.os.Bundle;
import android.util.Log;
import java.util.Map;
/**
* This is an example implementation of the {@link android.app.Instrumentation}
* class, allowing you to run tests against application code. The
* instrumentation implementation here is loaded into the application's
* process, for controlling and monitoring what it does.
*/
public class ContactsSelectInstrumentation extends Instrumentation {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments);
// When this instrumentation is created, we simply want to start
// its test code off in a separate thread, which will call back
// to us in onStart().
start();
}
@Override
public void onStart() {
super.onStart();
// First start the activity we are instrumenting -- the contacts
// list.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(getTargetContext(),
"com.android.phone.Dialer");
Activity activity = startActivitySync(intent);
// This is the Activity object that was started, to do with as we want.
Log.i("ContactsSelectInstrumentation", "Started: " + activity);
// Monitor for the expected start activity call.
ActivityMonitor am = addMonitor(IntentFilter.create(
Intent.ACTION_VIEW, Contacts.People.CONTENT_ITEM_TYPE), null, true);
// We are going to enqueue a couple key events to simulate the user
// selecting an item in the list.
sendKeySync(new KeyEvent(
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN));
sendKeySync(new KeyEvent(
KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN));
sendKeySync(new KeyEvent(
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER));
sendKeySync(new KeyEvent(
KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER));
// Was the expected activity started?
if (checkMonitorHit(am, 1)) {
Log.i("ContactsSelectInstrumentation", "Activity started!");
} else {
Log.i("ContactsSelectInstrumentation", "*** ACTIVITY NOT STARTED!");
}
// And we are done!
Log.i("ContactsSelectInstrumentation", "Done!");
finish(Activity.RESULT_OK, null);
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
/**
* <h3>Dialog Activity</h3>
*
* <p>This demonstrates the how to write an activity that looks like
* a pop-up dialog with a custom theme using a different text color.</p>
*/
public class CustomDialogActivity extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/dialog_activity.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.custom_dialog_activity);
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.android.apis.R;
/**
* Example of how to use a custom title {@link android.view.Window#FEATURE_CUSTOM_TITLE}.
* <h3>CustomTitle</h3>
<p>This demonstrates how a custom title can be used.</p>
<h4>Demo</h4>
App/Title/Custom Title
<h4>Source files</h4>
* <table class="LinkTable">
* <tr>
* <td >src/com.example.android.apis/app/CustomTitle.java</td>
* <td >The Custom Title implementation</td>
* </tr>
* <tr>
* <td >/res/any/layout/custom_title.xml</td>
* <td >Defines contents of the screen</td>
* </tr>
* </table>
*/
public class CustomTitle extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView(int)} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.custom_title);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
final TextView leftText = (TextView) findViewById(R.id.left_text);
final TextView rightText = (TextView) findViewById(R.id.right_text);
final EditText leftTextEdit = (EditText) findViewById(R.id.left_text_edit);
final EditText rightTextEdit = (EditText) findViewById(R.id.right_text_edit);
Button leftButton = (Button) findViewById(R.id.left_text_button);
Button rightButton = (Button) findViewById(R.id.right_text_button);
leftButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
leftText.setText(leftTextEdit.getText());
}
});
rightButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rightText.setText(rightTextEdit.getText());
}
});
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.ApiDemosApplication;
import com.example.android.apis.R;
import android.app.Application;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
/**
* This activity is an example of a simple settings screen that has default
* values.
* <p>
* In order for the default values to be populated into the
* {@link SharedPreferences} (from the preferences XML file), the client must
* call
* {@link PreferenceManager#setDefaultValues(android.content.Context, int, boolean)}.
* <p>
* This should be called early, typically when the application is first created.
* This ensures any of the application's activities, services, etc. will have
* the default values present, even if the user has not wandered into the
* application's settings. For ApiDemos, this is {@link ApiDemosApplication},
* and you can find the call to
* {@link PreferenceManager#setDefaultValues(android.content.Context, int, boolean)}
* in its {@link ApiDemosApplication#onCreate() onCreate}.
*/
public class DefaultValues extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.default_values);
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import com.example.android.apis.R;
/**
* <h3>Dialog Activity</h3>
*
* <p>This demonstrates the how to write an activity that looks like
* a pop-up dialog.</p>
*/
public class DialogActivity extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
// See assets/res/any/layout/dialog_activity.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.dialog_activity);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
android.R.drawable.ic_dialog_alert);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
/**
* Example of removing yourself from the history stack after forwarding to
* another activity.
*/
public class ForwardTarget extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.forward_target);
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* <p>Example of removing yourself from the history stack after forwarding to
* another activity. This can be useful, for example, to implement
a confirmation dialog before the user goes on to another activity -- once the
user has confirmed this operation, they should not see the dialog again if they
go back from it.</p>
<p>Note that another way to implement a confirmation dialog would be as
an activity that returns a result to its caller. Either approach can be
useful depending on how it makes sense to structure the application.</p>
<h4>Demo</h4>
App/Activity/Receive Result
<h4>Source files</h4>
<table class="LinkTable">
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/Forwarding.java</td>
<td class="DescrColumn">Forwards the user to another activity when its button is pressed</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/forwarding.xml</td>
<td class="DescrColumn">Defines contents of the Forwarding screen</td>
</tr>
</table>
*/
public class Forwarding extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.forwarding);
// Watch for button clicks.
Button goButton = (Button)findViewById(R.id.go);
goButton.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener()
{
public void onClick(View v)
{
// Here we start the next activity, and then call finish()
// so that our own will stop running and be removed from the
// history stack.
Intent intent = new Intent();
intent.setClass(Forwarding.this, ForwardTarget.class);
startActivity(intent);
finish();
}
};
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
/**
* Simple example of writing an application Activity.
* Hello World</a></h3>
<p>This demonstrates the basic code needed to write a Screen activity.</p>
<h4>Demo</h4>
App/Activity/Hello World
<h4>Source files</h4>
* <table class="LinkTable">
* <tr>
* <td >src/com.example.android.apis/app/HelloWorld.java</td>
* <td >The Hello World Screen implementation</td>
* </tr>
* <tr>
* <td >/res/any/layout/hello_world.xml</td>
* <td >Defines contents of the screen</td>
* </tr>
* </table>
*/
public class HelloWorld extends Activity
{
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/hello_world.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.hello_world);
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.app.IRemoteServiceCallback;
/**
* Example of defining an interface for calling on to a remote service
* (running in another process).
*/
interface IRemoteService {
/**
* Often you want to allow a service to call back to its clients.
* This shows how to do so, by registering a callback interface with
* the service.
*/
void registerCallback(IRemoteServiceCallback cb);
/**
* Remove a previously registered callback interface.
*/
void unregisterCallback(IRemoteServiceCallback cb);
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
/**
* Example of a callback interface used by IRemoteService to send
* synchronous notifications back to its clients. Note that this is a
* one-way interface so the server does not block waiting for the client.
*/
oneway interface IRemoteServiceCallback {
/**
* Called when the service has a new value for you.
*/
void valueChanged(int value);
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
/**
* Example of a secondary interface associated with a service. (Note that
* the interface itself doesn't impact, it is just a matter of how you
* retrieve it from the service.)
*/
interface ISecondary {
/**
* Request the PID of this service, to do evil things with it.
*/
int getPid();
/**
* This demonstrates the basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class IncomingMessage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.incoming_message);
Button button = (Button) findViewById(R.id.notify);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
showToast();
showNotification();
}
});
}
/**
* The toast pops up a quick message to the user showing what could be
* the text of an incoming message. It uses a custom view to do so.
*/
protected void showToast() {
// create the view
View view = inflateView(R.layout.incoming_message_panel);
// set the text in the view
TextView tv = (TextView)view.findViewById(R.id.message);
tv.setText("khtx. meet u for dinner. cul8r");
// show the toast
Toast toast = new Toast(this);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
private View inflateView(int resource) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return vi.inflate(resource, null);
}
/**
* The notification is the icon and associated expanded entry in the
* status bar.
*/
protected void showNotification() {
// look up the notification manager service
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// The details of our fake message
CharSequence from = "Joe";
CharSequence message = "kthx. meet u for dinner. cul8r";
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, IncomingMessageView.class), 0);
// The ticker text, this uses a formatted string so our message could be localized
String tickerText = getString(R.string.imcoming_message_ticker_text, message);
// construct the Notification object.
Notification notif = new Notification(R.drawable.stat_sample, tickerText,
System.currentTimeMillis());
// Set the info for the views that show in the notification panel.
notif.setLatestEventInfo(this, from, message, contentIntent);
// after a 100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ms.
notif.vibrate = new long[] { 100, 250, 100, 500};
// Note that we use R.layout.incoming_message_panel as the ID for
// the notification. It could be any integer you want, but we use
// the convention of using a resource id for a string related to
// the notification. It will always be a unique number within your
// application.
nm.notify(R.string.imcoming_message_ticker_text, notif);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import java.util.Map;
/**
* This activity is run as the click activity for {@link IncomingMessage}.
* When it comes up, it also clears the notification, because the "message"
* has been "read."
*/
public class IncomingMessageView extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.incoming_message_view);
// look up the notification manager service
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// cancel the notification that we started in IncomingMessage
nm.cancel(R.string.imcoming_message_ticker_text);
}
}

View File

@@ -0,0 +1,141 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;
import com.example.android.apis.R;
/**
* This Activity actually handles two stages of a launcher shortcut's life cycle.
*
* 1. Your application offers to provide shortcuts to the launcher. When
* the user installs a shortcut, an activity within your application
* generates the actual shortcut and returns it to the launcher, where it
* is shown to the user as an icon.
*
* 2. Any time the user clicks on an installed shortcut, an intent is sent.
* Typically this would then be handled as necessary by an activity within
* your application.
*
* We handle stage 1 (creating a shortcut) by simply sending back the information (in the form
* of an {@link android.content.Intent} that the launcher will use to create the shortcut.
*
* You can also implement this in an interactive way, by having your activity actually present
* UI for the user to select the specific nature of the shortcut, such as a contact, picture, URL,
* media item, or action.
*
* We handle stage 2 (responding to a shortcut) in this sample by simply displaying the contents
* of the incoming {@link android.content.Intent}.
*
* In a real application, you would probably use the shortcut intent to display specific content
* or start a particular operation.
*/
public class LauncherShortcuts extends Activity {
private static final String EXTRA_KEY = "com.example.android.apis.app.LauncherShortcuts";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Resolve the intent
final Intent intent = getIntent();
final String action = intent.getAction();
// If the intent is a request to create a shortcut, we'll do that and exit
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
setupShortcut();
finish();
return;
}
// If we weren't launched with a CREATE_SHORTCUT intent, simply put up an informative
// display.
// Inflate our UI from its XML layout description.
setContentView(R.layout.launcher_shortcuts);
// Provide a lightweight view of the Intent that launched us
TextView intentInfo = (TextView) findViewById(R.id.txt_shortcut_intent);
String info = intent.toString();
String extra = intent.getStringExtra(EXTRA_KEY);
if (extra != null) {
info = info + " " + extra;
}
intentInfo.setText(info);
}
/**
* This function creates a shortcut and returns it to the caller. There are actually two
* intents that you will send back.
*
* The first intent serves as a container for the shortcut and is returned to the launcher by
* setResult(). This intent must contain three fields:
*
* <ul>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_INTENT} The shortcut intent.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_NAME} The text that will be displayed with
* the shortcut.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} The shortcut's icon, if provided as a
* bitmap, <i>or</i> {@link android.content.Intent#EXTRA_SHORTCUT_ICON_RESOURCE} if provided as
* a drawable resource.</li>
* </ul>
*
* If you use a simple drawable resource, note that you must wrapper it using
* {@link android.content.Intent.ShortcutIconResource}, as shown below. This is required so
* that the launcher can access resources that are stored in your application's .apk file. If
* you return a bitmap, such as a thumbnail, you can simply put the bitmap into the extras
* bundle using {@link android.content.Intent#EXTRA_SHORTCUT_ICON}.
*
* The shortcut intent can be any intent that you wish the launcher to send, when the user
* clicks on the shortcut. Typically this will be {@link android.content.Intent#ACTION_VIEW}
* with an appropriate Uri for your content, but any Intent will work here as long as it
* triggers the desired action within your Activity.
*/
private void setupShortcut() {
// First, set up the shortcut intent. For this example, we simply create an intent that
// will bring us directly back to this activity. A more typical implementation would use a
// data Uri in order to display a more specific result, or a custom action in order to
// launch a specific operation.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, this.getClass().getName());
shortcutIntent.putExtra(EXTRA_KEY, "ApiDemos Provided This Shortcut");
// Then, set up the container intent (the response to the caller)
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_name));
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
this, R.drawable.app_sample_code);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
/**
* Demonstrates launching a PreferenceActivity and grabbing a value it saved.
*/
public class LaunchingPreferences extends Activity implements OnClickListener {
private static final int REQUEST_CODE_PREFERENCES = 1;
private TextView mCounterText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* If this were my app's main activity, I would load the default values
* so they're set even if the user does not go into the preferences
* screen. Another good place to call this method would be from a
* subclass of Application, so your default values would be loaded
* regardless of entry into your application (for example, a service or
* activity).
*/
PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
// Simple layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// Create a simple button that will launch the preferences
Button launchPreferences = new Button(this);
launchPreferences.setText(getString(R.string.launch_preference_activity));
launchPreferences.setOnClickListener(this);
layout.addView(launchPreferences, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
mCounterText = new TextView(this);
layout.addView(mCounterText, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
updateCounterText();
}
public void onClick(View v) {
// When the button is clicked, launch an activity through this intent
Intent launchPreferencesIntent = new Intent().setClass(this, AdvancedPreferences.class);
// Make it a subactivity so we know when it returns
startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// The preferences returned if the request code is what we had given
// earlier in startSubActivity
if (requestCode == REQUEST_CODE_PREFERENCES) {
// Read a sample value they have set
updateCounterText();
}
}
private void updateCounterText() {
// Since we're in the same package, we can use this context to get
// the default shared preferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
final int counter = sharedPref.getInt(AdvancedPreferences.KEY_MY_PREFERENCE, 0);
mCounterText.setText(getString(R.string.counter_value_is) + " " + counter);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.os.RemoteException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.android.apis.R;
/**
* Front-end for launching {@link LocalSampleInstrumentation} example
* instrumentation class.
*/
public class LocalSample extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_sample);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.go);
button.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener() {
public void onClick(View v) {
startInstrumentation(new ComponentName(LocalSample.this,
LocalSampleInstrumentation.class), null, null);
}
};
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.view.KeyEvent;
import android.os.Bundle;
import android.util.Log;
import java.util.Map;
/**
* This is an example implementation of the {@link android.app.Instrumentation}
* class demonstrating instrumentation against one of this application's sample
* activities.
*/
public class LocalSampleInstrumentation extends Instrumentation {
public abstract static class ActivityRunnable implements Runnable {
public final Activity activity;
public ActivityRunnable(Activity _activity) {
activity = _activity;
}
}
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments);
// When this instrumentation is created, we simply want to start
// its test code off in a separate thread, which will call back
// to us in onStart().
start();
}
@Override
public void onStart() {
super.onStart();
// First start the activity we are instrumenting -- the save/restore
// state sample, which has a nice edit text into which we can write
// text.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(getTargetContext(), SaveRestoreState.class);
SaveRestoreState activity = (SaveRestoreState)startActivitySync(intent);
// This is the Activity object that was started, to do with as we want.
Log.i("LocalSampleInstrumentation",
"Initial text: " + activity.getSavedText());
// Clear the text so we start fresh.
runOnMainSync(new ActivityRunnable(activity) {
public void run() {
((SaveRestoreState)activity).setSavedText("");
}
});
// Act like the user is typing some text.
sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT));
sendCharacterSync(KeyEvent.KEYCODE_H);
sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT));
sendCharacterSync(KeyEvent.KEYCODE_E);
sendCharacterSync(KeyEvent.KEYCODE_L);
sendCharacterSync(KeyEvent.KEYCODE_L);
sendCharacterSync(KeyEvent.KEYCODE_O);
// Wait for the activity to finish all of its processing.
waitForIdleSync();
// Retrieve the text we should have written...
Log.i("LocalSampleInstrumentation",
"Final text: " + activity.getSavedText());
// And we are done!
Log.i("ContactsFilterInstrumentation", "Done!");
finish(Activity.RESULT_OK, null);
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.widget.Toast;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
/**
* This is an example of implementing an application service that runs locally
* in the same process as the application. The {@link LocalServiceController}
* and {@link LocalServiceBinding} classes show how to interact with the
* service.
*
* <p>Notice the use of the {@link NotificationManager} when interesting things
* happen in the service. This is generally how background services should
* interact with the user, rather than doing something more disruptive such as
* calling startActivity().
*/
public class LocalService extends Service {
private NotificationManager mNM;
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(R.string.local_service_started);
// Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.local_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LocalServiceController.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label),
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.local_service_started, notification);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* <p>Example of binding and unbinding to the {@link LocalService}.
* This demonstrates the implementation of a service which the client will
* bind to, receiving an object through which it can communicate with the service.</p>
*/
public class LocalServiceBinding extends Activity {
private boolean mIsBound;
private LocalService mBoundService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_binding);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder)service).getService();
// Tell the user about this for our demo.
Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(LocalServiceBinding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
};
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* <p>Example of explicitly starting and stopping the {@link LocalService}.
* This demonstrates the implementation of a service that runs in the same
* process as the rest of the application, which is explicitly started and stopped
* as desired.</p>
*/
public class LocalServiceController extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_controller);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.start);
button.setOnClickListener(mStartListener);
button = (Button)findViewById(R.id.stop);
button.setOnClickListener(mStopListener);
}
private OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v)
{
// Make sure the service is started. It will continue running
// until someone calls stopService(). The Intent we use to find
// the service explicitly specifies our service component, because
// we want it running in our own process and don't want other
// applications to replace it.
startService(new Intent(LocalServiceController.this,
LocalService.class));
}
};
private OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v)
{
// Cancel a previous call to startService(). Note that the
// service will not actually stop at this point if there are
// still bound clients.
stopService(new Intent(LocalServiceController.this,
LocalService.class));
}
};
}

View File

@@ -0,0 +1,177 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* Demonstrates inflating menus from XML. There are different menu XML resources
* that the user can choose to inflate. First, select an example resource from
* the spinner, and then hit the menu button. To choose another, back out of the
* activity and start over.
*/
public class MenuInflateFromXml extends Activity {
/**
* Different example menu resources.
*/
private static final int sMenuExampleResources[] = {
R.menu.title_only, R.menu.title_icon, R.menu.submenu, R.menu.groups,
R.menu.checkable, R.menu.shortcuts, R.menu.order, R.menu.category_order,
R.menu.visible, R.menu.disabled
};
/**
* Names corresponding to the different example menu resources.
*/
private static final String sMenuExampleNames[] = {
"Title only", "Title and Icon", "Submenu", "Groups",
"Checkable", "Shortcuts", "Order", "Category and Order",
"Visible", "Disabled"
};
/**
* Lets the user choose a menu resource.
*/
private Spinner mSpinner;
/**
* Shown as instructions.
*/
private TextView mInstructionsText;
/**
* Safe to hold on to this.
*/
private Menu mMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a simple layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Create the spinner to allow the user to choose a menu XML
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sMenuExampleNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner = new Spinner(this);
// When programmatically creating views, make sure to set an ID
// so it will automatically save its instance state
mSpinner.setId(R.id.spinner);
mSpinner.setAdapter(adapter);
// Add the spinner
layout.addView(mSpinner,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
// Create help text
mInstructionsText = new TextView(this);
mInstructionsText.setText(getResources().getString(
R.string.menu_from_xml_instructions_press_menu));
// Add the help, make it look decent
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 10, 10, 10);
layout.addView(mInstructionsText, lp);
// Set the layout as our content view
setContentView(layout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Hold on to this
mMenu = menu;
// Inflate the currently selected menu XML resource.
MenuInflater inflater = getMenuInflater();
inflater.inflate(sMenuExampleResources[mSpinner.getSelectedItemPosition()], menu);
// Disable the spinner since we've already created the menu and the user
// can no longer pick a different menu XML.
mSpinner.setEnabled(false);
// Change instructions
mInstructionsText.setText(getResources().getString(
R.string.menu_from_xml_instructions_go_back));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// For "Title only": Examples of matching an ID with one assigned in
// the XML
case R.id.jump:
Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_SHORT).show();
return true;
case R.id.dive:
Toast.makeText(this, "Dive into the water!", Toast.LENGTH_SHORT).show();
return true;
// For "Groups": Toggle visibility of grouped menu items with
// nongrouped menu items
case R.id.browser_visibility:
// The refresh item is part of the browser group
final boolean shouldShowBrowser = !mMenu.findItem(R.id.refresh).isVisible();
mMenu.setGroupVisible(R.id.browser, shouldShowBrowser);
break;
case R.id.email_visibility:
// The reply item is part of the email group
final boolean shouldShowEmail = !mMenu.findItem(R.id.reply).isVisible();
mMenu.setGroupVisible(R.id.email, shouldShowEmail);
break;
// Generic catch all for all the other menu resources
default:
// Don't toast text when a submenu is clicked
if (!item.hasSubMenu()) {
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
break;
}
return false;
}
}

View File

@@ -0,0 +1,171 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
/**
* This is an example of a custom preference type. The preference counts the
* number of clicks it has received and stores/retrieves it from the storage.
*/
public class MyPreference extends Preference {
private int mClickCounter;
// This is the constructor called by the inflater
public MyPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setWidgetLayoutResource(R.layout.preference_widget_mypreference);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
// Set our custom views inside the layout
final TextView myTextView = (TextView) view.findViewById(R.id.mypreference_widget);
if (myTextView != null) {
myTextView.setText(String.valueOf(mClickCounter));
}
}
@Override
protected void onClick() {
int newValue = mClickCounter + 1;
// Give the client a chance to ignore this change if they deem it
// invalid
if (!callChangeListener(newValue)) {
// They don't want the value to be set
return;
}
// Increment counter
mClickCounter = newValue;
// Save to persistent storage (this method will make sure this
// preference should be persistent, along with other useful checks)
persistInt(mClickCounter);
// Data has changed, notify so UI can be refreshed!
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// This preference type's value type is Integer, so we read the default
// value from the attributes as an Integer.
return a.getInteger(index, 0);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
// Restore state
mClickCounter = getPersistedInt(mClickCounter);
} else {
// Set state
int value = (Integer) defaultValue;
mClickCounter = value;
persistInt(value);
}
}
@Override
protected Parcelable onSaveInstanceState() {
/*
* Suppose a client uses this preference type without persisting. We
* must save the instance state so it is able to, for example, survive
* orientation changes.
*/
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
// Save the instance state
final SavedState myState = new SavedState(superState);
myState.clickCounter = mClickCounter;
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
// Restore the instance state
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
mClickCounter = myState.clickCounter;
notifyChanged();
}
/**
* SavedState, a subclass of {@link BaseSavedState}, will store the state
* of MyPreference, a subclass of Preference.
* <p>
* It is important to always call through to super methods.
*/
private static class SavedState extends BaseSavedState {
int clickCounter;
public SavedState(Parcel source) {
super(source);
// Restore the click counter
clickCounter = source.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
// Save the click counter
dest.writeInt(clickCounter);
}
public SavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.widget.Button;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
/**
* When you push the button on this Activity, it creates a {@link Toast} object and
* using the Toast method.
* @see Toast
* @see Toast#makeText(android.content.Context,int,int)
* @see Toast#makeText(android.content.Context,java.lang.CharSequence,int)
* @see Toast#LENGTH_SHORT
* @see Toast#LENGTH_LONG
*/
public class NotifyWithText extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_with_text);
Button button;
// short notification
button = (Button) findViewById(R.id.short_notify);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// Note that we create the Toast object and call the show() method
// on it all on one line. Most uses look like this, but there
// are other methods on Toast that you can call to configure how
// it appears.
//
// Note also that we use the version of makeText that takes a
// resource id (R.string.short_notification_text). There is also
// a version that takes a CharSequence if you must construct
// the text yourself.
Toast.makeText(NotifyWithText.this, R.string.short_notification_text,
Toast.LENGTH_SHORT).show();
}
});
// long notification
// The only difference here is that the notification stays up longer.
// You might want to use this if there is more text that they're going
// to read.
button = (Button) findViewById(R.id.long_notify);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Toast.makeText(NotifyWithText.this, R.string.long_notification_text,
Toast.LENGTH_LONG).show();
}
});
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Controller to start and stop a service. The serivce will update a status bar
* notification every 5 seconds for a minute.
*/
public class NotifyingController extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notifying_controller);
Button button = (Button) findViewById(R.id.notifyStart);
button.setOnClickListener(mStartListener);
button = (Button) findViewById(R.id.notifyStop);
button.setOnClickListener(mStopListener);
}
private OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
startService(new Intent(NotifyingController.this,
NotifyingService.class));
}
};
private OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
stopService(new Intent(NotifyingController.this,
NotifyingService.class));
}
};
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.ConditionVariable;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.RemoteViews;
/**
* This is an example of service that will update its status bar balloon
* every 5 seconds for a minute.
*
*/
public class NotifyingService extends Service {
// Use a layout id for a unique identifier
private static int MOOD_NOTIFICATIONS = R.layout.status_bar_notifications;
// variable which controls the notification thread
private ConditionVariable mCondition;
@Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
Thread notifyingThread = new Thread(null, mTask, "NotifyingService");
mCondition = new ConditionVariable(false);
notifyingThread.start();
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(MOOD_NOTIFICATIONS);
// Stop the thread from generating further notifications
mCondition.open();
}
private Runnable mTask = new Runnable() {
public void run() {
for (int i = 0; i < 4; ++i) {
showNotification(R.drawable.stat_happy,
R.string.status_bar_notifications_happy_message);
if (mCondition.block(5 * 1000))
break;
showNotification(R.drawable.stat_neutral,
R.string.status_bar_notifications_ok_message);
if (mCondition.block(5 * 1000))
break;
showNotification(R.drawable.stat_sad,
R.string.status_bar_notifications_sad_message);
if (mCondition.block(5 * 1000))
break;
}
// Done with our work... stop the service!
NotifyingService.this.stopSelf();
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private void showNotification(int moodId, int textId) {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(textId);
// Set the icon, scrolling text and timestamp.
// Note that in this example, we pass null for tickerText. We update the icon enough that
// it is distracting to show the ticker text every time it changes. We strongly suggest
// that you do this as well. (Think of of the "New hardware found" or "Network connection
// changed" messages that always pop up)
Notification notification = new Notification(moodId, null, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, NotifyingController.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.status_bar_notifications_mood_title),
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(MOOD_NOTIFICATIONS, notification);
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
private NotificationManager mNM;
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.widget.Toast;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
/**
* This is an example of implement an {@link BroadcastReceiver} for an alarm that
* should occur once.
* <p>
* When the alarm goes off, we show a <i>Toast</i>, a quick message.
*/
public class OneShotAlarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, R.string.one_shot_received, Toast.LENGTH_SHORT).show();
}
}

View File

@@ -0,0 +1,128 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
/**
* Simple example of using persistent preferences to retain a screen's state.
* <p>This can be used as an alternative to the normal
* <code>onSaveInstanceState()</code> mechanism, if you
* wish the state to persist even after an activity is finished.</p>
*
* <p>Note that using this approach requires more care, since you are sharing
* the persistent state potentially across multiple instances of the activity.
* In particular, if you allow a new instance of the activity to be launched
* directly on top of the existing instance, the state can get out of sync
* because the new instance is resumed before the old one is paused.</p>
*
* <p>For any persistent state that is not simplistic, a content
* provider is often a better choice.</p>
*
* <p>In this example we are currently saving and restoring the state of the
* top text editor, but not of the bottom text editor. You can see the difference
* by editing the two text fields, then going back from the activity and
* starting it again.</p>
*
* <h4>Demo</h4>
* App/Activity/Save &amp; Restore State
*
* <h4>Source files</h4>
* <table class="LinkTable">
* <tr>
* <td class="LinkColumn">src/com.example.android.apis/app/PersistentState.java</td>
* <td class="DescrColumn">The Save/Restore Screen implementation</td>
* </tr>
* <tr>
* <td class="LinkColumn">/res/any/layout/save_restore_state.xml</td>
* <td class="DescrColumn">Defines contents of the screen</td>
* </tr>
* </table>
*
*/
public class PersistentState extends Activity
{
/**
* Initialization of the Activity after it is first created. Here we use
* {@link android.app.Activity#setContentView setContentView()} to set up
* the Activity's content, and retrieve the EditText widget whose state we
* will persistent.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/save_restore_state.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.save_restore_state);
// Set message to be appropriate for this screen.
((TextView)findViewById(R.id.msg)).setText(R.string.persistent_msg);
// Retrieve the EditText widget whose state we will save.
mSaved = (EditText)findViewById(R.id.saved);
}
/**
* Upon being resumed we can retrieve the current state. This allows us
* to update the state if it was changed at any time while paused.
*/
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = getPreferences(0);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
mSaved.setSelection(selectionStart, selectionEnd);
}
}
}
/**
* Any time we are paused we need to save away the current state, so it
* will be restored correctly when we are resumed.
*/
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
}
private EditText mSaved;
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PreferenceDependencies extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_dependencies);
}
}

View File

@@ -0,0 +1,143 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import com.example.android.apis.R;
public class PreferencesFromCode extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPreferenceScreen(createPreferenceHierarchy());
}
private PreferenceScreen createPreferenceHierarchy() {
// Root
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
// Inline preferences
PreferenceCategory inlinePrefCat = new PreferenceCategory(this);
inlinePrefCat.setTitle(R.string.inline_preferences);
root.addPreference(inlinePrefCat);
// Toggle preference
CheckBoxPreference togglePref = new CheckBoxPreference(this);
togglePref.setKey("toggle_preference");
togglePref.setTitle(R.string.title_toggle_preference);
togglePref.setSummary(R.string.summary_toggle_preference);
inlinePrefCat.addPreference(togglePref);
// Dialog based preferences
PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
dialogBasedPrefCat.setTitle(R.string.dialog_based_preferences);
root.addPreference(dialogBasedPrefCat);
// Edit text preference
EditTextPreference editTextPref = new EditTextPreference(this);
editTextPref.setDialogTitle(R.string.dialog_title_edittext_preference);
editTextPref.setKey("edittext_preference");
editTextPref.setTitle(R.string.title_edittext_preference);
editTextPref.setSummary(R.string.summary_edittext_preference);
dialogBasedPrefCat.addPreference(editTextPref);
// List preference
ListPreference listPref = new ListPreference(this);
listPref.setEntries(R.array.entries_list_preference);
listPref.setEntryValues(R.array.entryvalues_list_preference);
listPref.setDialogTitle(R.string.dialog_title_list_preference);
listPref.setKey("list_preference");
listPref.setTitle(R.string.title_list_preference);
listPref.setSummary(R.string.summary_list_preference);
dialogBasedPrefCat.addPreference(listPref);
// Launch preferences
PreferenceCategory launchPrefCat = new PreferenceCategory(this);
launchPrefCat.setTitle(R.string.launch_preferences);
root.addPreference(launchPrefCat);
/*
* The Preferences screenPref serves as a screen break (similar to page
* break in word processing). Like for other preference types, we assign
* a key here so that it is able to save and restore its instance state.
*/
// Screen preference
PreferenceScreen screenPref = getPreferenceManager().createPreferenceScreen(this);
screenPref.setKey("screen_preference");
screenPref.setTitle(R.string.title_screen_preference);
screenPref.setSummary(R.string.summary_screen_preference);
launchPrefCat.addPreference(screenPref);
/*
* You can add more preferences to screenPref that will be shown on the
* next screen.
*/
// Example of next screen toggle preference
CheckBoxPreference nextScreenCheckBoxPref = new CheckBoxPreference(this);
nextScreenCheckBoxPref.setKey("next_screen_toggle_preference");
nextScreenCheckBoxPref.setTitle(R.string.title_next_screen_toggle_preference);
nextScreenCheckBoxPref.setSummary(R.string.summary_next_screen_toggle_preference);
screenPref.addPreference(nextScreenCheckBoxPref);
// Intent preference
PreferenceScreen intentPref = getPreferenceManager().createPreferenceScreen(this);
intentPref.setIntent(new Intent().setAction(Intent.ACTION_VIEW)
.setData(Uri.parse("http://www.android.com")));
intentPref.setTitle(R.string.title_intent_preference);
intentPref.setSummary(R.string.summary_intent_preference);
launchPrefCat.addPreference(intentPref);
// Preference attributes
PreferenceCategory prefAttrsCat = new PreferenceCategory(this);
prefAttrsCat.setTitle(R.string.preference_attributes);
root.addPreference(prefAttrsCat);
// Visual parent toggle preference
CheckBoxPreference parentCheckBoxPref = new CheckBoxPreference(this);
parentCheckBoxPref.setTitle(R.string.title_parent_preference);
parentCheckBoxPref.setSummary(R.string.summary_parent_preference);
prefAttrsCat.addPreference(parentCheckBoxPref);
// Visual child toggle preference
// See res/values/attrs.xml for the <declare-styleable> that defines
// TogglePrefAttrs.
TypedArray a = obtainStyledAttributes(R.styleable.TogglePrefAttrs);
CheckBoxPreference childCheckBoxPref = new CheckBoxPreference(this);
childCheckBoxPref.setTitle(R.string.title_child_preference);
childCheckBoxPref.setSummary(R.string.summary_child_preference);
childCheckBoxPref.setLayoutResource(
a.getResourceId(R.styleable.TogglePrefAttrs_android_preferenceLayoutChild,
0));
prefAttrsCat.addPreference(childCheckBoxPref);
a.recycle();
return root;
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
public class PreferencesFromXml extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import java.util.Map;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.util.Map;
/**
* Shows how an activity can send data to its launching activity when done.y.
* <p>This can be used, for example, to implement a dialog alowing the user to
pick an e-mail address or image -- the picking activity sends the selected
data back to the originating activity when done.</p>
<p>The example here is composed of two activities: ReceiveResult launches
the picking activity and receives its results; SendResult allows the user
to pick something and sends the selection back to its caller. Implementing
this functionality involves the
{@link android.app.Activity#setResult setResult()} method for sending a
result and
{@link android.app.Activity#onActivityResult onActivityResult()} to
receive it.</p>
<h4>Demo</h4>
App/Activity/Receive Result
<h4>Source files</h4>
<table class="LinkTable">
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/ReceiveResult.java</td>
<td class="DescrColumn">Launches pick activity and receives its result</td>
</tr>
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/SendResult.java</td>
<td class="DescrColumn">Allows user to pick an option and sends it back to its caller</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/receive_result.xml</td>
<td class="DescrColumn">Defines contents of the ReceiveResult screen</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/send_result.xml</td>
<td class="DescrColumn">Defines contents of the SendResult screen</td>
</tr>
</table>
*/
public class ReceiveResult extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/hello_world.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.receive_result);
// Retrieve the TextView widget that will display results.
mResults = (TextView)findViewById(R.id.results);
// This allows us to later extend the text buffer.
mResults.setText(mResults.getText(), TextView.BufferType.EDITABLE);
// Watch for button clicks.
Button getButton = (Button)findViewById(R.id.get);
getButton.setOnClickListener(mGetListener);
}
/**
* This method is called when the sending activity has finished, with the
* result it supplied.
*
* @param requestCode The original request code as given to
* startActivity().
* @param resultCode From sending activity as per setResult().
* @param data From sending activity as per setResult().
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// You can use the requestCode to select between multiple child
// activities you may have started. Here there is only one thing
// we launch.
if (requestCode == GET_CODE) {
// We will be adding to our text.
Editable text = (Editable)mResults.getText();
// This is a standard resultCode that is sent back if the
// activity doesn't supply an explicit result. It will also
// be returned if the activity failed to launch.
if (resultCode == RESULT_CANCELED) {
text.append("(cancelled)");
// Our protocol with the sending activity is that it will send
// text in 'data' as its result.
} else {
text.append("(okay ");
text.append(Integer.toString(resultCode));
text.append(") ");
if (data != null) {
text.append(data.getAction());
}
}
text.append("\n");
}
}
// Definition of the one requestCode we use for receiving resuls.
static final private int GET_CODE = 0;
private OnClickListener mGetListener = new OnClickListener() {
public void onClick(View v) {
// Start the activity whose result we want to retrieve. The
// result will come back with request code GET_CODE.
Intent intent = new Intent(ReceiveResult.this, SendResult.class);
startActivityForResult(intent, GET_CODE);
}
};
private TextView mResults;
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Entry into our redirection example, describing what will happen.
*/
public class RedirectEnter extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.redirect_enter);
// Watch for button clicks.
Button goButton = (Button)findViewById(R.id.go);
goButton.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener()
{
public void onClick(View v)
{
// Here we start up the main entry point of our redirection
// example.
Intent intent = new Intent(RedirectEnter.this, RedirectMain.class);
startActivity(intent);
}
};
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Sub-activity that is executed by the redirection example when input is needed
* from the user.
*/
public class RedirectGetter extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.redirect_getter);
// Watch for button clicks.
Button applyButton = (Button)findViewById(R.id.apply);
applyButton.setOnClickListener(mApplyListener);
// The text being set.
mText = (TextView)findViewById(R.id.text);
}
private final boolean loadPrefs()
{
// Retrieve the current redirect values.
// NOTE: because this preference is shared between multiple
// activities, you must be careful about when you read or write
// it in order to keep from stepping on yourself.
SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
mTextPref = preferences.getString("text", null);
if (mTextPref != null) {
mText.setText(mTextPref);
return true;
}
return false;
}
private OnClickListener mApplyListener = new OnClickListener()
{
public void onClick(View v)
{
SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("text", mText.getText().toString());
if (editor.commit()) {
setResult(RESULT_OK);
}
finish();
}
};
private String mTextPref;
TextView mText;
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Entry into our redirection example, describing what will happen.
*/
public class RedirectMain extends Activity {
static final int INIT_TEXT_REQUEST = 0;
static final int NEW_TEXT_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.redirect_main);
// Watch for button clicks.
Button clearButton = (Button)findViewById(R.id.clear);
clearButton.setOnClickListener(mClearListener);
Button newButton = (Button)findViewById(R.id.newView);
newButton.setOnClickListener(mNewListener);
// Retrieve the current text preference. If there is no text
// preference set, we need to get it from the user by invoking the
// activity that retrieves it. To do this cleanly, we will
// temporarily hide our own activity so it is not displayed until the
// result is returned.
if (!loadPrefs()) {
Intent intent = new Intent(this, RedirectGetter.class);
startActivityForResult(intent, INIT_TEXT_REQUEST);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == INIT_TEXT_REQUEST) {
// If the request was cancelled, then we are cancelled as well.
if (resultCode == RESULT_CANCELED) {
finish();
// Otherwise, there now should be text... reload the prefs,
// and show our UI. (Optionally we could verify that the text
// is now set and exit if it isn't.)
} else {
loadPrefs();
}
} else if (requestCode == NEW_TEXT_REQUEST) {
// In this case we are just changing the text, so if it was
// cancelled then we can leave things as-is.
if (resultCode != RESULT_CANCELED) {
loadPrefs();
}
}
}
private final boolean loadPrefs() {
// Retrieve the current redirect values.
// NOTE: because this preference is shared between multiple
// activities, you must be careful about when you read or write
// it in order to keep from stepping on yourself.
SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
mTextPref = preferences.getString("text", null);
if (mTextPref != null) {
TextView text = (TextView)findViewById(R.id.text);
text.setText(mTextPref);
return true;
}
return false;
}
private OnClickListener mClearListener = new OnClickListener() {
public void onClick(View v) {
// Erase the preferences and exit!
SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
preferences.edit().remove("text").commit();
finish();
}
};
private OnClickListener mNewListener = new OnClickListener() {
public void onClick(View v) {
// Retrieve new text preferences.
Intent intent = new Intent(RedirectMain.this, RedirectGetter.class);
startActivityForResult(intent, NEW_TEXT_REQUEST);
}
};
private String mTextPref;
}

View File

@@ -0,0 +1,185 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.RemoteException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.widget.Toast;
import java.util.HashMap;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
/**
* This is an example of implementing an application service that runs in a
* different process than the application. Because it can be in another
* process, we must use IPC to interact with it. The
* {@link RemoteServiceController} and {@link RemoteServiceBinding} classes
* show how to interact with the service.
*/
public class RemoteService extends Service {
/**
* This is a list of callbacks that have been registered with the
* service. Note that this is package scoped (instead of private) so
* that it can be accessed more efficiently from inner classes.
*/
final RemoteCallbackList<IRemoteServiceCallback> mCallbacks
= new RemoteCallbackList<IRemoteServiceCallback>();
int mValue = 0;
NotificationManager mNM;
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting.
showNotification();
// While this service is running, it will continually increment a
// number. Send the first message that is used to perform the
// increment.
mHandler.sendEmptyMessage(REPORT_MSG);
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(R.string.remote_service_started);
// Tell the user we stopped.
Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
// Unregister all callbacks.
mCallbacks.kill();
// Remove the next pending message to increment the counter, stopping
// the increment loop.
mHandler.removeMessages(REPORT_MSG);
}
// BEGIN_INCLUDE(exposing_a_service)
@Override
public IBinder onBind(Intent intent) {
// Select the interface to return. If your service only implements
// a single interface, you can just return it here without checking
// the Intent.
if (IRemoteService.class.getName().equals(intent.getAction())) {
return mBinder;
}
if (ISecondary.class.getName().equals(intent.getAction())) {
return mSecondaryBinder;
}
return null;
}
/**
* The IRemoteInterface is defined through IDL
*/
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public void registerCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.register(cb);
}
public void unregisterCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.unregister(cb);
}
};
/**
* A secondary interface to the service.
*/
private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
public int getPid() {
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
}
};
// END_INCLUDE(exposing_a_service)
private static final int REPORT_MSG = 1;
/**
* Our Handler used to execute operations on the main thread. This is used
* to schedule increments of our value.
*/
private final Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
// It is time to bump the value!
case REPORT_MSG: {
// Up it goes.
int value = ++mValue;
// Broadcast to all clients the new value.
final int N = mCallbacks.beginBroadcast();
for (int i=0; i<N; i++) {
try {
mCallbacks.getBroadcastItem(i).valueChanged(value);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
mCallbacks.finishBroadcast();
// Repeat every 1 second.
sendMessageDelayed(obtainMessage(REPORT_MSG), 1*1000);
} break;
default:
super.handleMessage(msg);
}
}
};
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.remote_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LocalServiceController.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
text, contentIntent);
// Send the notification.
// We use a string id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.remote_service_started, notification);
}
}

View File

@@ -0,0 +1,241 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
// BEGIN_INCLUDE(exposing_a_service)
public class RemoteServiceBinding extends Activity {
/** The primary interface we will be calling on the service. */
IRemoteService mService = null;
/** Another interface we use on the service. */
ISecondary mSecondaryService = null;
Button mKillButton;
TextView mCallbackText;
private boolean mIsBound;
/**
* Standard initialization of this activity. Set up the UI, then wait
* for the user to poke it before doing anything.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_service_binding);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
mKillButton = (Button)findViewById(R.id.kill);
mKillButton.setOnClickListener(mKillListener);
mKillButton.setEnabled(false);
mCallbackText = (TextView)findViewById(R.id.callback);
mCallbackText.setText("Not attached.");
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = IRemoteService.Stub.asInterface(service);
mKillButton.setEnabled(true);
mCallbackText.setText("Attached.");
// We want to monitor the service for as long as we are
// connected to it.
try {
mService.registerCallback(mCallback);
} catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
// As part of the sample, tell the user what happened.
Toast.makeText(RemoteServiceBinding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mKillButton.setEnabled(false);
mCallbackText.setText("Disconnected.");
// As part of the sample, tell the user what happened.
Toast.makeText(RemoteServiceBinding.this, R.string.remote_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
/**
* Class for interacting with the secondary interface of the service.
*/
private ServiceConnection mSecondaryConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// Connecting to a secondary interface is the same as any
// other interface.
mSecondaryService = ISecondary.Stub.asInterface(service);
mKillButton.setEnabled(true);
}
public void onServiceDisconnected(ComponentName className) {
mSecondaryService = null;
mKillButton.setEnabled(false);
}
};
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
// Establish a couple connections with the service, binding
// by interface names. This allows other applications to be
// installed that replace the remote service by implementing
// the same interface.
bindService(new Intent(IRemoteService.class.getName()),
mConnection, Context.BIND_AUTO_CREATE);
bindService(new Intent(ISecondary.class.getName()),
mSecondaryConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
mCallbackText.setText("Binding.");
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
if (mIsBound) {
// If we have received the service, and hence registered with
// it, then now is the time to unregister.
if (mService != null) {
try {
mService.unregisterCallback(mCallback);
} catch (RemoteException e) {
// There is nothing special we need to do if the service
// has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
unbindService(mSecondaryConnection);
mKillButton.setEnabled(false);
mIsBound = false;
mCallbackText.setText("Unbinding.");
}
}
};
private OnClickListener mKillListener = new OnClickListener() {
public void onClick(View v) {
// To kill the process hosting our service, we need to know its
// PID. Conveniently our service has a call that will return
// to us that information.
if (mSecondaryService != null) {
try {
int pid = mSecondaryService.getPid();
// Note that, though this API allows us to request to
// kill any process based on its PID, the kernel will
// still impose standard restrictions on which PIDs you
// are actually able to kill. Typically this means only
// the process running your application and any additional
// processes created by that app as shown here; packages
// sharing a common UID will also be able to kill each
// other's processes.
Process.killProcess(pid);
mCallbackText.setText("Killed service process.");
} catch (RemoteException ex) {
// Recover gracefully from the process hosting the
// server dying.
// Just for purposes of the sample, put up a notification.
Toast.makeText(RemoteServiceBinding.this,
R.string.remote_call_failed,
Toast.LENGTH_SHORT).show();
}
}
}
};
// ----------------------------------------------------------------------
// Code showing how to deal with callbacks.
// ----------------------------------------------------------------------
/**
* This implementation is used to receive callbacks from the remote
* service.
*/
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
/**
* This is called by the remote service regularly to tell us about
* new values. Note that IPC calls are dispatched through a thread
* pool running in each process, so the code executing here will
* NOT be running in our main thread like most other things -- so,
* to update the UI, we need to use a Handler to hop over there.
*/
public void valueChanged(int value) {
mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
}
};
private static final int BUMP_MSG = 1;
private Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case BUMP_MSG:
mCallbackText.setText("Received from service: " + msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
};
}
// END_INCLUDE(exposing_a_service)

View File

@@ -0,0 +1,65 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class RemoteServiceController extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_service_controller);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.start);
button.setOnClickListener(mStartListener);
button = (Button)findViewById(R.id.stop);
button.setOnClickListener(mStopListener);
}
private OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
// Make sure the service is started. It will continue running
// until someone calls stopService().
// We use an action code here, instead of explictly supplying
// the component name, so that other packages can replace
// the service.
startService(new Intent(
"com.example.android.apis.app.REMOTE_SERVICE"));
}
};
private OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
// Cancel a previous call to startService(). Note that the
// service will not actually stop at this point if there are
// still bound clients.
stopService(new Intent(
"com.example.android.apis.app.REMOTE_SERVICE"));
}
};
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.widget.Toast;
/**
* This is an example of implement an {@link BroadcastReceiver} for an alarm that
* should occur once.
*/
public class RepeatingAlarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, R.string.repeating_received, Toast.LENGTH_SHORT).show();
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
/**
* <p>Demonstrates required behavior of saving and restoring dynamic activity
* state, so that an activity will restart with the correct state if it is
* stopped by the system.</p>
*
* <p>In general, any activity that has been paused may be stopped by the system
* at any time if it needs more resources for the currently running activity.
* To handle this, before being paused the
* {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} method is called before
* an activity is paused, allowing it to supply its current state. If that
* activity then needs to be stopped, upon restarting it will receive its
* last saved state in
* {@link android.app.Activity#onCreate}.</p>
* <p>In this example we are currently saving and restoring the state of the
* top text editor, but not of the bottom text editor. You can see the difference
* by editing the two text fields, then going to a couple different
* applications while the demo is running and then returning back to it. The
* system takes care of saving a view's state as long as an id has been
* assigned to the view, so we assign an ID to the view being saved but not
* one to the view that isn't being saved.</p>
* <h4>Demo</h4>
* App/Activity/Save &amp; Restore State
* <h4>Source files</h4>
* <table class="LinkTable">
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/SaveRestoreState.java</td>
<td class="DescrColumn">The Save/Restore Screen implementation</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/save_restore_state.xml</td>
<td class="DescrColumn">Defines contents of the screen</td>
</tr>
</table>
*/
public class SaveRestoreState extends Activity
{
/**
* Initialization of the Activity after it is first created. Here we use
* {@link android.app.Activity#setContentView setContentView()} to set up
* the Activity's content, and retrieve the EditText widget whose state we
* will save/restore.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/save_restore_state.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.save_restore_state);
// Set message to be appropriate for this screen.
((TextView)findViewById(R.id.msg)).setText(R.string.save_restore_msg);
}
/**
* Retrieve the text that is currently in the "saved" editor.
*/
CharSequence getSavedText() {
return ((EditText)findViewById(R.id.saved)).getText();
}
/**
* Change the text that is currently in the "saved" editor.
*/
void setSavedText(CharSequence text) {
((EditText)findViewById(R.id.saved)).setText(text);
}
}

View File

@@ -0,0 +1,214 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class SearchInvoke extends Activity
{
// UI elements
Button mStartSearch;
Spinner mMenuMode;
EditText mQueryPrefill;
EditText mQueryAppData;
// Menu mode spinner choices
// This list must match the list found in samples/ApiDemos/res/values/arrays.xml
final static int MENUMODE_SEARCH_KEY = 0;
final static int MENUMODE_MENU_ITEM = 1;
final static int MENUMODE_TYPE_TO_SEARCH = 2;
final static int MENUMODE_DISABLED = 3;
/**
* Called with the activity is first created.
*
* We aren't doing anything special in this implementation, other than
* the usual activity setup code.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.search_invoke);
// Get display items for later interaction
mStartSearch = (Button) findViewById(R.id.btn_start_search);
mMenuMode = (Spinner) findViewById(R.id.spinner_menu_mode);
mQueryPrefill = (EditText) findViewById(R.id.txt_query_prefill);
mQueryAppData = (EditText) findViewById(R.id.txt_query_appdata);
// Populate items
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.search_menuModes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mMenuMode.setAdapter(adapter);
// Create listener for the menu mode dropdown. We use this to demonstrate control
// of the default keys handler in every Activity. More typically, you will simply set
// the default key mode in your activity's onCreate() handler.
mMenuMode.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
if (position == MENUMODE_TYPE_TO_SEARCH) {
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
} else {
setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
}
}
public void onNothingSelected(AdapterView<?> parent) {
setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
}
});
// Attach actions to buttons
mStartSearch.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
onSearchRequested();
}
});
}
/**
* Called when your activity's options menu needs to be updated.
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item;
// first, get rid of our menus (if any)
menu.removeItem(0);
// next, add back item(s) based on current menu mode
switch (mMenuMode.getSelectedItemPosition())
{
case MENUMODE_SEARCH_KEY:
item = menu.add( 0, 0, 0, "(Search Key)");
break;
case MENUMODE_MENU_ITEM:
item = menu.add( 0, 0, 0, "Search");
item.setAlphabeticShortcut(SearchManager.MENU_KEY);
break;
case MENUMODE_TYPE_TO_SEARCH:
item = menu.add( 0, 0, 0, "(Type-To-Search)");
break;
case MENUMODE_DISABLED:
item = menu.add( 0, 0, 0, "(Disabled)");
break;
}
return true;
}
/** Handle the menu item selections */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
switch (mMenuMode.getSelectedItemPosition()) {
case MENUMODE_SEARCH_KEY:
new AlertDialog.Builder(this)
.setMessage("To invoke search, dismiss this dialog and press the search key" +
" (F5 on the simulator).")
.setPositiveButton("OK", null)
.show();
break;
case MENUMODE_MENU_ITEM:
onSearchRequested();
break;
case MENUMODE_TYPE_TO_SEARCH:
new AlertDialog.Builder(this)
.setMessage("To invoke search, dismiss this dialog and start typing.")
.setPositiveButton("OK", null)
.show();
break;
case MENUMODE_DISABLED:
new AlertDialog.Builder(this)
.setMessage("You have disabled search.")
.setPositiveButton("OK", null)
.show();
break;
}
break;
}
return super.onOptionsItemSelected(item);
}
/**
* This hook is called when the user signals the desire to start a search.
*
* By overriding this hook we can insert local or context-specific data.
*
* @return Returns true if search launched, false if activity blocks it
*/
@Override
public boolean onSearchRequested() {
// If your application absolutely must disable search, do it here.
if (mMenuMode.getSelectedItemPosition() == MENUMODE_DISABLED) {
return false;
}
// It's possible to prefill the query string before launching the search
// UI. For this demo, we simply copy it from the user input field.
// For most applications, you can simply pass null to startSearch() to
// open the UI with an empty query string.
final String queryPrefill = mQueryPrefill.getText().toString();
// Next, set up a bundle to send context-specific search data (if any)
// The bundle can contain any number of elements, using any number of keys;
// For this Api Demo we copy a string from the user input field, and store
// it in the bundle as a string with the key "demo_key".
// For most applications, you can simply pass null to startSearch().
Bundle appDataBundle = null;
final String queryAppDataString = mQueryAppData.getText().toString();
if (queryAppDataString != null) {
appDataBundle = new Bundle();
appDataBundle.putString("demo_key", queryAppDataString);
}
// Now call the Activity member function that invokes the Search Manager UI.
startSearch(queryPrefill, false, appDataBundle, false);
// Returning true indicates that we did launch the search, instead of blocking it.
return true;
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.widget.TextView;
public class SearchQueryResults extends Activity
{
// UI elements
TextView mQueryText;
TextView mAppDataText;
TextView mDeliveredByText;
/** Called with the activity is first created.
*
* After the typical activity setup code, we check to see if we were launched
* with the ACTION_SEARCH intent, and if so, we handle it.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.search_query_results);
// Get active display items for later updates
mQueryText = (TextView) findViewById(R.id.txt_query);
mAppDataText = (TextView) findViewById(R.id.txt_appdata);
mDeliveredByText = (TextView) findViewById(R.id.txt_deliveredby);
// get and process search query here
final Intent queryIntent = getIntent();
final String queryAction = queryIntent.getAction();
if (Intent.ACTION_SEARCH.equals(queryAction)) {
doSearchQuery(queryIntent, "onCreate()");
}
else {
mDeliveredByText.setText("onCreate(), but no ACTION_SEARCH intent");
}
}
/**
* Called when new intent is delivered.
*
* This is where we check the incoming intent for a query string.
*
* @param newIntent The intent used to restart this activity
*/
@Override
public void onNewIntent(final Intent newIntent) {
super.onNewIntent(newIntent);
// get and process search query here
final Intent queryIntent = getIntent();
final String queryAction = queryIntent.getAction();
if (Intent.ACTION_SEARCH.equals(queryAction)) {
doSearchQuery(queryIntent, "onNewIntent()");
}
else {
mDeliveredByText.setText("onNewIntent(), but no ACTION_SEARCH intent");
}
}
/**
* Generic search handler.
*
* In a "real" application, you would use the query string to select results from
* your data source, and present a list of those results to the user.
*/
private void doSearchQuery(final Intent queryIntent, final String entryPoint) {
// The search query is provided as an "extra" string in the query intent
final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
mQueryText.setText(queryString);
// Record the query string in the recent queries suggestions provider.
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
suggestions.saveRecentQuery(queryString, null);
// If your application provides context data for its searches,
// you will receive it as an "extra" bundle in the query intent.
// The bundle can contain any number of elements, using any number of keys;
// For this Api Demo we're just using a single string, stored using "demo key".
final Bundle appData = queryIntent.getBundleExtra(SearchManager.APP_DATA);
if (appData == null) {
mAppDataText.setText("<no app data bundle>");
}
if (appData != null) {
String testStr = appData.getString("demo_key");
mAppDataText.setText((testStr == null) ? "<no app data>" : testStr);
}
// Report the method by which we were called.
mDeliveredByText.setText(entryPoint);
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.content.SearchRecentSuggestionsProvider;
/**
* To create a search suggestions provider using the built-in recent queries mode,
* simply extend SearchRecentSuggestionsProvider as shown here, and configure with
* a unique authority and the mode you with to use. For more information, see
* {@link android.content.SearchRecentSuggestionsProvider}.
*/
public class SearchSuggestionSampleProvider extends SearchRecentSuggestionsProvider {
/**
* This is the provider authority identifier. The same string must appear in your
* Manifest file, and any time you instantiate a
* {@link android.provider.SearchRecentSuggestions} helper class.
*/
final static String AUTHORITY = "com.example.android.apis.SuggestionProvider";
/**
* These flags determine the operating mode of the suggestions provider. This value should
* not change from run to run, because when it does change, your suggestions database may
* be wiped.
*/
final static int MODE = DATABASE_MODE_QUERIES;
/**
* The main job of the constructor is to call {@link #setupSuggestions(String, int)} with the
* appropriate configuration values.
*/
public SearchSuggestionSampleProvider() {
super();
setupSuggestions(AUTHORITY, MODE);
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Example of receiving a result from another activity.
*/
public class SendResult extends Activity
{
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/hello_world.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.send_result);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(mCorkyListener);
button = (Button)findViewById(R.id.violet);
button.setOnClickListener(mVioletListener);
}
private OnClickListener mCorkyListener = new OnClickListener()
{
public void onClick(View v)
{
// To send a result, simply call setResult() before your
// activity is finished.
setResult(RESULT_OK, (new Intent()).setAction("Corky!"));
finish();
}
};
private OnClickListener mVioletListener = new OnClickListener()
{
public void onClick(View v)
{
// To send a result, simply call setResult() before your
// activity is finished.
setResult(RESULT_OK, (new Intent()).setAction("Violet!"));
finish();
}
};
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.example.android.apis.R;
/**
* This is an example of implementing an application service that runs locally
* in the same process as the application. The {@link ServiceStartArgumentsController}
* class shows how to interact with the service.
*
* <p>Notice the use of the {@link NotificationManager} when interesting things
* happen in the service. This is generally how background services should
* interact with the user, rather than doing something more disruptive such as
* calling startActivity().
*/
public class ServiceStartArguments extends Service
{
private NotificationManager mNM;
private Intent mInvokeIntent;
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg)
{
Bundle arguments = (Bundle)msg.obj;
String txt = getResources()
.getString(R.string.service_arguments_started);
txt = txt + arguments.getString("name");
Log.i("ServiceStartArguments", "Message: " + msg + ", " + txt);
showNotification();
// Normally we would do some work here... for our sample, we will
// just sleep for 10 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
stopSelf(msg.arg1);
}
};
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// This is who should be launched if the user selects our persistent
// notification.
mInvokeIntent = new Intent(this, ServiceStartArgumentsController.class);
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
HandlerThread thread = new HandlerThread("ServiceStartArguments");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("ServiceStartArguments",
"Starting #" + startId + ": " + intent.getExtras());
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent.getExtras();
mServiceHandler.sendMessage(msg);
Log.i("ServiceStartArguments", "Sending: " + msg);
}
@Override
public void onDestroy() {
mServiceLooper.quit();
// Cancel the persistent notification.
mNM.cancel(R.string.service_arguments_started);
// Tell the user we stopped.
Toast.makeText(ServiceStartArguments.this, R.string.service_arguments_stopped,
Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.service_arguments_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmService.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.service_start_arguments_label),
text, contentIntent);
// Send the notification.
// We use a string id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.service_arguments_started, notification);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.android.apis.R;
import java.util.HashMap;
/**
* Example of explicitly starting the {@link ServiceStartArguments}.
*/
public class ServiceStartArgumentsController extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_start_arguments_controller);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.start1);
button.setOnClickListener(mStart1Listener);
button = (Button)findViewById(R.id.start2);
button.setOnClickListener(mStart2Listener);
button = (Button)findViewById(R.id.start3);
button.setOnClickListener(mStart3Listener);
}
private OnClickListener mStart1Listener = new OnClickListener() {
public void onClick(View v) {
startService(new Intent(ServiceStartArgumentsController.this,
ServiceStartArguments.class).putExtra("name", "One"));
}
};
private OnClickListener mStart2Listener = new OnClickListener() {
public void onClick(View v) {
startService(new Intent(ServiceStartArgumentsController.this,
ServiceStartArguments.class).putExtra("name", "Two"));
}
};
private OnClickListener mStart3Listener = new OnClickListener() {
public void onClick(View v) {
startService(new Intent(ServiceStartArgumentsController.this,
ServiceStartArguments.class).putExtra("name", "Three"));
}
};
}

View File

@@ -0,0 +1,230 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
/**
* Demonstrates adding notifications to the status bar
*/
public class StatusBarNotifications extends Activity {
private NotificationManager mNotificationManager;
// Use our layout id for a unique identifier
private static int MOOD_NOTIFICATIONS = R.layout.status_bar_notifications;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.status_bar_notifications);
Button button;
// Get the notification manager serivce.
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
button = (Button) findViewById(R.id.happy);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMood(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message,
false);
}
});
button = (Button) findViewById(R.id.neutral);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMood(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message,
false);
}
});
button = (Button) findViewById(R.id.sad);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMood(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message, false);
}
});
button = (Button) findViewById(R.id.happyMarquee);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMood(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message,
true);
}
});
button = (Button) findViewById(R.id.neutralMarquee);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMood(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message, true);
}
});
button = (Button) findViewById(R.id.sadMarquee);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMood(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message, true);
}
});
button = (Button) findViewById(R.id.happyViews);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMoodView(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message);
}
});
button = (Button) findViewById(R.id.neutralViews);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMoodView(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message);
}
});
button = (Button) findViewById(R.id.sadViews);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setMoodView(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message);
}
});
button = (Button) findViewById(R.id.defaultSound);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setDefault(Notification.DEFAULT_SOUND);
}
});
button = (Button) findViewById(R.id.defaultVibrate);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setDefault(Notification.DEFAULT_VIBRATE);
}
});
button = (Button) findViewById(R.id.defaultAll);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setDefault(Notification.DEFAULT_ALL);
}
});
button = (Button) findViewById(R.id.clear);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mNotificationManager.cancel(R.layout.status_bar_notifications);
}
});
}
private void setMood(int moodId, int textId, boolean showTicker) {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(textId);
// choose the ticker text
String tickerText = showTicker ? getString(textId) : null;
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(moodId, tickerText,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, StatusBarNotifications.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.status_bar_notifications_mood_title),
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNotificationManager.notify(R.layout.status_bar_notifications, notification);
}
private void setMoodView(int moodId, int textId) {
// Instead of the normal constructor, we're going to use the one with no args and fill
// in all of the data ourselves. The normal one uses the default layout for notifications.
// You probably want that in most cases, but if you want to do something custom, you
// can set the contentView field to your own RemoteViews object.
Notification notif = new Notification();
// This is who should be launched if the user selects our notification.
notif.contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, StatusBarNotifications.class), 0);
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(textId);
notif.tickerText = text;
// the icon for the status bar
notif.icon = moodId;
// our custom view
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.status_bar_balloon);
contentView.setTextViewText(R.id.text, text);
contentView.setImageViewResource(R.id.icon, moodId);
notif.contentView = contentView;
// we use a string id because is a unique number. we use it later to cancel the
// notification
mNotificationManager.notify(R.layout.status_bar_notifications, notif);
}
private void setDefault(int defaults) {
// This method sets the defaults on the notification before posting it.
// This is who should be launched if the user selects our notification.
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, StatusBarNotifications.class), 0);
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.status_bar_notifications_happy_message);
final Notification notification = new Notification(
R.drawable.stat_happy, // the icon for the status bar
text, // the text to display in the ticker
System.currentTimeMillis()); // the timestamp for the notification
notification.setLatestEventInfo(
this, // the context to use
getText(R.string.status_bar_notifications_mood_title),
// the title for the notification
text, // the details to display in the notification
contentIntent); // the contentIntent (see above)
notification.defaults = defaults;
mNotificationManager.notify(
R.layout.status_bar_notifications, // we use a string id because it is a unique
// number. we use it later to cancel the
notification); // notification
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
/**
* <h3>Translucent Activity</h3>
*
* <p>This demonstrates the how to write an activity that is translucent,
* allowing windows underneath to show through.</p>
*/
public class TranslucentActivity extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/translucent_background.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.translucent_background);
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.WindowManager;
/**
* <h3>Fancy Blur Activity</h3>
*
* <p>This demonstrates the how to write an activity that is translucent,
* allowing windows underneath to show through, with a fancy blur
* compositing effect.</p>
*/
public class TranslucentBlurActivity extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle icicle) {
// Be sure to call the super class.
super.onCreate(icicle);
// Have the system blur any windows behind this one.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
// See assets/res/any/layout/translucent_background.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.translucent_background);
}
}

View File

@@ -0,0 +1,145 @@
<h3>Activity</h3>
<dl>
<dt><a href="HelloWorld.html">Hello World</a></dt>
<dd>Demonstrates a basic screen activity.
<dl>
<dt>Code:
<dd> <a href="HelloWorld.html">HelloWorld.java</a>
<dt>Layout:
<dd> <a href="{@docRoot}samples/ApiDemos/res/layout/hello_world.html">
hello_world.xml</a>
</dl>
</dd>
<dt><a href="SaveRestoreState.html">Save &amp; Restore State</a></dt>
<dd>Demonstrates how an activity should save state when it is paused.</dd>
<dt><a href="PersistentState.html">Persistent State</a></dt>
<dd>Demonstrates how you can save and restore preferences, which are stored
even after the user closes the application. </dd>
<dt><a href="ReceiveResult.html">Receive Result</a></dt>
<dd>Demonstrates how an activity screen can return a result to the
activity that opened it. </dd>
<dt><a href="Forwarding.html">Forwarding</a></dt>
<dd>Demonstrates opening a new activity and removing the current activity
from the history stack, so that when the user later presses BACK they will
not see the intermediate activity.</dd>
<dt><a href="RedirectEnter.html">Redirection</a></dt>
<dd>Demonstrates how to save data to preferences and use it to determine
which activity to open next.</dd>
<dt><a href="TranslucentActivity.html">Translucent</a></dt>
<dd>Demonstrates how to make an activity with a transparent background. </dd>
<dt><a href="TranslucentFancyActivity.html">TranslucentFancy</a></dt>
<dd>Demonstrates how to make an activity with a transparent background with
a special effect (blur). </dd>
</dl>
<h3>Service</h3>
<dl>
<dt><a href="LocalServiceController.html">Local Service Controller</a></dt>
<dd>Starts and stops the service class
<a href="LocalService.html">LocalService</a> that runs in the same
process as the activity, to demonstrate a service's
lifecycle when using {@link android.content.Context#startService
Context.startService} and {@link android.content.Context#stopService
Context.stopService}.</dd>
<dt><a href="LocalServiceBinding.html">Local Service Binding</a></dt>
<dd>Demonstrates binding to a service class
<a href="LocalService.html">LocalService</a> that runs in the same
process as the activity, to demonstrate using the
{@link android.content.Context#bindService Context.bindService} and
{@link android.content.Context#unbindService Context.unindService}
methods with a service. This also shows how you can simplify working
with a service when you know it will only run in your own process.</dd>
<dt><a href="RemoteServiceController.html">Remote Service Controller</a></dt>
<dd>Demonstrates starting a service in a separate process, by assigning
<code>android:process=&quot;:remote&quot;</code> to the service in the
AndroidManifest.xml file. </dd>
<dt><a href="RemoteServiceBinding.html">Remote Service Binding</a></dt>
<dd>Demonstrates binding to a remote service, similar to the Local Service
Binding sample, but illustrating the additional work (defining aidl
interfaces) needed to interact with a service in another process. Also
shows how a service can publish multiple interfaces and implement
callbacks to its clients.</dd>
<dt><a href="ServiceStartArgumentsController.html">Service Start Arguments Controller</a></dt>
<dd>Demonstrates how you can use a Service as a job queue, where you
submit jobs to it with {@link android.content.Context#startService
Context.startService} instead of binding to the service. Such a service
automatically stops itself once all jobs have been processed. This can be
a very convenient way to interact with a service when you do not need
a result back from it.
<dl>
<dt>Code:
<dd> <a href="ServiceStartArgumentsController.html">ServiceStartArgumentsController.java</a>
<dd> <a href="ServiceStartArguments.html">ServiceStartArguments.java</a>
<dt>Layout:
<dd> <a href="{@docRoot}samples/ApiDemos/res/layout/service_start_arguments_controller.html">
service_start_arguments_controller.xml</a>
</dl>
</dd>
</dl>
<h3>Alarm</h3>
<dl>
<dt><a href="AlarmController.html">Alarm Controller</a></dt>
<dd>Demonstrates two ways you can schedule alarms: a one-shot alarm that
will happen once at a given time, and a repeating alarm that will happen
first at a given time and then continually trigger at regular intervals
after that.
<dl>
<dt>Code:
<dd> <a href="AlarmController.html">AlarmController.java</a>
<dd> <a href="OneShotAlarm.html">OneShotAlarm.java</a>
<dd> <a href="RepeatingAlarm.html">RepeatingAlarm.java</a>
<dt>Layout:
<dd> <a href="{@docRoot}samples/ApiDemos/res/layout/alarm_controller.html">
alarm_controller.xml</a>
</dl>
</dd>
<dt><a href="AlarmService.html">Alarm Service</a></dt>
<dd>Demonstrates how you can schedule an alarm that causes a service to
be started. This is useful when you want to schedule alarms that initiate
long-running operations, such as retrieving recent e-mails.
<dl>
<dt>Code:
<dd> <a href="AlarmService.html">AlarmService.java</a>
<dd> <a href="AlarmService_Service.html">AlarmService_Service.java</a>
<dt>Layout:
<dd> <a href="{@docRoot}samples/ApiDemos/res/layout/alarm_service.html">
alarm_service.xml</a>
</dl>
</dd>
</dl>
<h3>Notification</h3>
<dl>
<dt><a href="NotifyWithText.html">NotifyWithText</a></dt>
<dd>Demonstrates popup notifications of varying length.</dd>
<dt><a href="IncomingMessage.html">IncomingMessage</a></dt>
<dd> Demonstrates sending persistent and transient notifications, with a View object in the notification. It also demonstrated inflating a View object from an XML layout resource. </dd>
</dl>
<h3>Search</h3>
<dl>
<dt><a href="SearchInvoke.html">SearchInvoke</a></dt>
<dd>Demonstrates various ways in which activities can launch the Search UI.</dd>
<dt><a href="SearchQueryResults.html">SearchQueryResults</a></dt>
<dd>Demonstrates an activity that receives Search intents and handles them.</dd>
<dt><a href="SearchSuggestionSampleProvider.html">SearchSuggestionSampleProvider</a></dt>
<dd>Demonstrates how to configure and use the built-in "recent queries" suggestion provider.</dd>
</dl>

View File

@@ -0,0 +1,48 @@
<html>
<head>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
<script type="text/javascript" src="http://www.corp.google.com/style/prettify.js"></script>
<script src="http://www.corp.google.com/eng/techpubs/include/navbar.js" type="text/javascript"></script>
</head>
<body>
<p>
Examples of how to use the android.app APIs.
<ol>
<li> Activities
- These examples show various ways you can use activities to implement an
application's user interface.
<ol>
<li> {@link com.android.samples.app.HelloWorld Hello World}
<li> {@link com.android.samples.app.SaveRestoreState Save &amp; Restore State}
<li>{@link com.android.samples.app.PersistentState Persistent State}
<li>{@link com.android.samples.app.ReceiveResult Receive Result}
<li>{@link com.android.samples.app.Forwarding Forwarding}
</ol>
<li> Services
- These examples show how you can implement application services, which
give you a way to run code in the background outside of the normal UI flow.
<ol>
<li>{@link com.android.samples.app.LocalServiceController Local Service
Controller}
<li>{@link com.android.samples.app.LocalServiceBinding Local Service Binding}
<li>{@link com.android.samples.app.RemoteServiceController Remote Service
Controller}
<li>{@link com.android.samples.app.RemoteServiceBinding Remote Service
Binding}
</ol>
<li> Alarms
- These examples show how you can use alarms to schedule background
events.
<ol>
<li>{@link com.android.samples.app.AlarmController Alarm Controller}
<li>{@link com.android.samples.app.AlarmService Alarm Service}
</ol>
</ol>
</body>
</html>