我是android studio的新手,我创建了一个使用GCM通知的Android webview应用程序。该应用程序有两个活动:
每当我显示activity_register时启动我的应用程序。我想在用户第一次成功登录后隐藏activity_register。
1)activity_register LOGIN WINDOW SCREEN
AndroidMainfest.xml
<application
android:name="com.eduapp.Controller"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<!-- Main Activity -->
<activity
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:theme="@android:style/Theme.NoTitleBar"
android:name="com.eduapp.MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name" >
</activity>
<!-- Register Activity -->
<activity
android:name="com.eduapp.RegisterActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.DELETE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="com.idrivecare.familypro" />
</intent-filter>
</activity>
MainActivity.java
public class MainActivity extends Activity {
// label to display gcm messages
TextView lblMessage;
Controller aController;
//----------------------------------------------------
private WebView webView;
private ProgressBar progress;
public Uri imageUri;
//-----------------------------------------------------
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
//-------------------ON-CREATE-START-------------------
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---------------------------------------------------------
//web settings
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
//progress bar setting
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
//load page settings
webView.setWebChromeClient(new MyWebViewClient());
// mWebView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://demo.eduapp.in/pages_admin");
//-------------------------------------------------------------------
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
aController = (Controller) getApplicationContext();
// Check if Internet present
if (!aController.isConnectingToInternet()) {
// Internet Connection is not present
aController.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest permissions was properly set
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
// Register custom Broadcast receiver to show messages on activity
registerReceiver(mHandleMessageReceiver, new IntentFilter(
Config.DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Register with GCM
GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);
} else {
// Device is already registered on GCM Server
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(),
"Already registered with GCM Server",
Toast.LENGTH_LONG).
show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
aController.register(context, name, email, regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
// execute AsyncTask
mRegisterTask.execute(null, null, null);
}
}
}
//-------------------ON-CREATE-END-------------------
// Create a broadcast receiver to get message and show on screen
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
aController.acquireWakeLock(getApplicationContext());
// Display message on the screen
lblMessage.append(newMessage + " ");
Toast.makeText(getApplicationContext(),
"Got Message: " + newMessage,
Toast.LENGTH_LONG).show();
// Releasing wake lock
aController.releaseWakeLock();
}
};
@Override
protected void onDestroy() {
// Cancel AsyncTask
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
// Unregister Broadcast Receiver
unregisterReceiver(mHandleMessageReceiver);
//Clear internal resources.
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
// Log.e("UnRegister Receiver Error","> " + e.getMessage());
}
super.onDestroy();
}
private class MyWebViewClient extends WebChromeClient
{
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
findViewById(R.id.imageLoading2).setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
} else {
findViewById(R.id.webView).setVisibility(View.VISIBLE);
MainActivity.this.progress.setProgress(0);
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
if (newProgress >= 100) {
progress.setVisibility(View.GONE);
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
} else {
progress.setVisibility(View.VISIBLE);
findViewById(R.id.imageLoading2).setVisibility(View.GONE);
findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
findViewById(R.id.webView).setVisibility(View.GONE);
}
}
}
// You can create external class extends with WebChromeClient
// Taking WebViewClient as inner class
// we will define openFileChooser for select file from camera or sdcard
}
@Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
RegisterActivity.java
public class RegisterActivity extends Activity {
// UI elements
EditText txtName;
EditText txtEmail;
// Register button
Button btnRegister;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
final Controller aController = (Controller) getApplicationContext();
// Check if Internet Connection present
if (!aController.isConnectingToInternet()) {
// Internet Connection is not present
aController.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if GCM configuration is set
if (Config.YOUR_SERVER_URL == null
|| Config.GOOGLE_SENDER_ID == null
|| Config.YOUR_SERVER_URL.length() == 0
|| Config.GOOGLE_SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
aController.showAlertDialog(RegisterActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
txtName = (EditText) findViewById(R.id.txtName);
txtEmail = (EditText) findViewById(R.id.txtEmail);
btnRegister = (Button) findViewById(R.id.btnRegister);
// Click event on Register button
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Get data from EditText
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
// Check if user filled the form
if(name.trim().length() > 0 && email.trim().length() > 0){
// Launch Main Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Registering user on our server
// Sending registraiton details to MainActivity
i.putExtra("name", name);
i.putExtra("email", email);
startActivity(i);
finish();
}else{
// user doen't filled that data
aController.showAlertDialog(RegisterActivity.this,
"Registration Error!",
"Please enter your details",
false);
}
}
});
}
}
Confing.java
public interface Config {
// CONSTANTS
static final String YOUR_SERVER_URL ="http://eduapp.in/hello/register.php";
// Google project id
static final String GOOGLE_SENDER_ID = "189074368474";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Android Example";
static final String DISPLAY_MESSAGE_ACTION ="com.eduapp.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
private Controller aController = null;
public GCMIntentService() {
// Call extended class Constructor GCMBaseIntentService
super(Config.GOOGLE_SENDER_ID);
}
/**
* Method called on device registered
**/
@Override
protected void onRegistered(Context context, String registrationId) {
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device registered: regId = " + registrationId);
aController.displayMessageOnScreen(context,
"Your device registred with GCM");
Log.d("NAME", MainActivity.name);
aController.register(context, MainActivity.name,
MainActivity.email, registrationId);
}
/**
* Method called on device unregistred
* */
@Override
protected void onUnregistered(Context context, String registrationId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device unregistered");
aController.displayMessageOnScreen(context,getString(R.string.gcm_unregistered));
aController.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message from GCM server
* */
@Override
protected void onMessage(Context context, Intent intent) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
@Override
protected void onDeletedMessages(Context context, int total) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
@Override
public void onError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received error: " + errorId);
aController.displayMessageOnScreen(context,
getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
aController.displayMessageOnScreen(context,
getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Create a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when2 = System.currentTimeMillis();
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder b = new NotificationCompat.Builder(context);
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(icon)
.setTicker("Eduapp.in")
.setContentTitle("New Notification")
.setContentText(message)
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
.setContentIntent(contentIntent)
.setContentInfo("Eduapp.in");
//context, title, message, intent,icon, message, when
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
}
}
答案 0 :(得分:1)
您需要创建会话才能执行此操作。会话将保留您首次登录时的详细信息,以便以后何时返回应用程序,用户名和密码已保存在应用程序中。这些显然嵌入在应用程序中的用户不可见。
我还会实现这样的想法,即用户可以在下次使用应用程序时注销并重新输入他/她的凭据。
Here是一个很好的教程,介绍了如何实现它。
希望这会有所帮助:)