1

Я новичок в студии android, и я создал приложение с веб-просмотром Android с использованием уведомлений GCM. Приложение имеет два вида деятельности:Скрыть страницу входа в систему после успешного входа в систему и показать main_activity в android

  1. activity_register (используется для нового пользователя для регистрации с приложением)
  2. activity_main (используются в качестве главного экрана приложения)

Когда я запускаю мое приложение каждый раз, когда отображается 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

использовать общие переменный для управления сеансами в андроиде, это поможет вам сохранить имя пользователя и пароль. не нажимайте пользователя на странице регистрации. сначала используйте некоторые другие действия и дайте варианты регистрации и входа там – sud

ответ

1

Вам необходимо создать сеанс, чтобы сделать это. Сессия будет содержать ваши данные от вашего первого входа, так что, когда вы вернетесь к приложению позже, имя пользователя и пароль уже будут сохранены в приложении. Они, очевидно, встроены в приложение, не видны пользователю.

Я также хотел бы реализовать идею о том, что пользователь может выйти из системы и повторно ввести свои учетные данные при следующем использовании приложения, если они того пожелают.

Here - отличное учебное пособие о том, как это реализовано.

Надеется, что это помогает :)

+1

эй спасибо, я получил решение для этого ..i ящика для моего приложения. –

Смежные вопросы