首页 文章 精选 留言 我的

精选列表

搜索[流程管理],共10000篇文章
优秀的个人博客,低调大师

03.源码阅读(Activity启动流程--android api 23)

(创建于2017/10/16) 关键词: ActivityThread ApplicationThread IActivityManager IApplicationThread Instrumentation ActivityManagerService ActivityStack 这篇是去年写的,前几天看了一下api26的源码,发现有些地方看的衔接不上,还是低版本的源码看起来轻松一些 先说一个接口: IActivityManager 对于我们要实现绕过androidmanifest检测启动一个没有注册的activity,I ActivityManager是一个很关键的接口,这里定义了安卓四大组件相关的一些方法,比如startActivity startService registerReceiver getContentResolver等等,我们最终的目的就是要通过动态代理实现对这个接口的代理从而拦截activity的启动,达到绕过配置文件检测的目的 Activity中 从startActivity开始可以找到这个方法 public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); if (ar != null) { mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); } 。。。。 Instrumentation中 public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); ActivityResult result = null; if (am.ignoreMatchingSpecificIntents()) { result = am.onStartActivity(intent); } if (result != null) { am.mHits++; return result; } else if (am.match(who, null, intent)) { am.mHits++; if (am.isBlocking()) { return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(); intent.prepareToLeaveProcess(who); int result = ActivityManager.getService() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; } 检测结果,异常捕获 /** @hide */ public static void checkStartActivityResult(int res, Object intent) { if (!ActivityManager.isStartResultFatalError(res)) { return; } switch (res) { case ActivityManager.START_INTENT_NOT_RESOLVED: case ActivityManager.START_CLASS_NOT_FOUND: if (intent instanceof Intent && ((Intent)intent).getComponent() != null) throw new ActivityNotFoundException( "Unable to find explicit activity class " + ((Intent)intent).getComponent().toShortString() + "; have you declared this activity in your AndroidManifest.xml?"); throw new ActivityNotFoundException( "No Activity found to handle " + intent); case ActivityManager.START_PERMISSION_DENIED: throw new SecurityException("Not allowed to start activity " + intent); case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: throw new AndroidRuntimeException( "FORWARD_RESULT_FLAG used while also requesting a result"); case ActivityManager.START_NOT_ACTIVITY: throw new IllegalArgumentException( "PendingIntent is not an activity"); case ActivityManager.START_NOT_VOICE_COMPATIBLE: throw new SecurityException( "Starting under voice control not allowed for: " + intent); case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION: throw new IllegalStateException( "Session calling startVoiceActivity does not match active session"); case ActivityManager.START_VOICE_HIDDEN_SESSION: throw new IllegalStateException( "Cannot start voice activity on a hidden session"); case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION: throw new IllegalStateException( "Session calling startAssistantActivity does not match active session"); case ActivityManager.START_ASSISTANT_HIDDEN_SESSION: throw new IllegalStateException( "Cannot start assistant activity on a hidden session"); case ActivityManager.START_CANCELED: throw new AndroidRuntimeException("Activity could not be started for " + intent); default: throw new AndroidRuntimeException("Unknown error code " + res + " when starting " + intent); } } 关键代码 int result = ActivityManager.getService() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); ActivityManagerNative.getService().startActivity是一个进程间的通信(看源码) 有的版本叫 ActivityManagerNative.getDefault().startActivity ActivityManager.getService() /** * @hide */ public static IActivityManager getService() { return IActivityManagerSingleton.get(); } IActivityManagerSingleton.get() private static final Singleton<IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>() { @Override protected IActivityManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am = IActivityManager.Stub.asInterface(b); return am; } }; Singleton 源码 public abstract class Singleton<T> { private T mInstance; protected abstract T create(); public final T get() { synchronized (this) { if (mInstance == null) { mInstance = create(); } return mInstance; } } } 也就是说ActivityManager.getService得到的是IActivityManager的一个实现类 这个实现类是ActivityManagerService ActivityManagerService中 @Override public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) { return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options, UserHandle.getCallingUserId()); } @Override public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) { enforceNotIsolatedCaller("startActivity"); userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, false, ALLOW_FULL_ONLY, "startActivity", null); // TODO: Switch to user app stacks here. return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, null, null, options, false, userId, null, null); } ActivityStackSupervisor中 final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration config, Bundle options, boolean ignoreTargetSecurity, int userId, IActivityContainer iContainer, TaskRecord inTask) { // Refuse possible leaked file descriptors if (intent != null && intent.hasFileDescriptors()) { throw new IllegalArgumentException("File descriptors passed in Intent"); } boolean componentSpecified = intent.getComponent() != null; // Don't modify the client's object! intent = new Intent(intent); // Collect information about the target of the Intent. ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId); ActivityContainer container = (ActivityContainer)iContainer; synchronized (mService) { if (container != null && container.mParentActivity != null && container.mParentActivity.state != RESUMED) { // Cannot start a child activity if the parent is not resumed. return ActivityManager.START_CANCELED; } final int realCallingPid = Binder.getCallingPid(); final int realCallingUid = Binder.getCallingUid(); int callingPid; if (callingUid >= 0) { callingPid = -1; } else if (caller == null) { callingPid = realCallingPid; callingUid = realCallingUid; } else { callingPid = callingUid = -1; } final ActivityStack stack; if (container == null || container.mStack.isOnHomeDisplay()) { stack = mFocusedStack; } else { stack = container.mStack; } stack.mConfigWillChange = config != null && mService.mConfiguration.diff(config) != 0; if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Starting activity when config will change = " + stack.mConfigWillChange); final long origId = Binder.clearCallingIdentity(); if (aInfo != null && (aInfo.applicationInfo.privateFlags &ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) { // This may be a heavy-weight process! Check to see if we already // have another, different heavy-weight process running. if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) { if (mService.mHeavyWeightProcess != null && (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid || !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) { int appCallingUid = callingUid; if (caller != null) { ProcessRecord callerApp = mService.getRecordForAppLocked(caller); if (callerApp != null) { appCallingUid = callerApp.info.uid; } else { Slog.w(TAG, "Unable to find app for caller " + caller + " (pid=" + callingPid + ") when starting: " + intent.toString()); ActivityOptions.abort(options); return ActivityManager.START_PERMISSION_DENIED; } } IIntentSender target = mService.getIntentSenderLocked( ActivityManager.INTENT_SENDER_ACTIVITY, "android", appCallingUid, userId, null, null, 0, new Intent[] { intent }, new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT, null); Intent newIntent = new Intent(); if (requestCode >= 0) { // Caller is requesting a result. newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true); } newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT, new IntentSender(target)); if (mService.mHeavyWeightProcess.activities.size() > 0) { ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0); newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP, hist.packageName); newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK, hist.task.taskId); } newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP, aInfo.packageName); newIntent.setFlags(intent.getFlags()); newIntent.setClassName("android", HeavyWeightSwitcherActivity.class.getName()); intent = newIntent; resolvedType = null; caller = null; callingUid = Binder.getCallingUid(); callingPid = Binder.getCallingPid(); componentSpecified = true; try { ResolveInfo rInfo = AppGlobals.getPackageManager().resolveIntent( intent, null, PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS, userId); aInfo = rInfo != null ? rInfo.activityInfo : null; aInfo = mService.getActivityInfoForUser(aInfo, userId); } catch (RemoteException e) { aInfo = null; } } } } int res = startActivityLocked(caller, intent, resolvedType, aInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity, componentSpecified, null, container, inTask); Binder.restoreCallingIdentity(origId); if (stack.mConfigWillChange) { // If the caller also wants to switch to a new configuration, // do so now. This allows a clean switch, as we are waiting // for the current activity to pause (so we will not destroy // it), and have not yet started the next activity. mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, "updateConfiguration()"); stack.mConfigWillChange = false; if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Updating to new configuration after starting activity."); mService.updateConfigurationLocked(config, null, false, false); } if (outResult != null) { outResult.result = res; if (res == ActivityManager.START_SUCCESS) { mWaitingActivityLaunched.add(outResult); do { try { mService.wait(); } catch (InterruptedException e) { } } while (!outResult.timeout && outResult.who == null); } else if (res == ActivityManager.START_TASK_TO_FRONT) { ActivityRecord r = stack.topRunningActivityLocked(null); if (r.nowVisible && r.state == RESUMED) { outResult.timeout = false; outResult.who = new ComponentName(r.info.packageName, r.info.name); outResult.totalTime = 0; outResult.thisTime = 0; } else { outResult.thisTime = SystemClock.uptimeMillis(); mWaitingActivityVisible.add(outResult); do { try { mService.wait(); } catch (InterruptedException e) { } } while (!outResult.timeout && outResult.who == null); } } } return res; } } final int startActivityLocked(IApplicationThread caller, Intent intent, String resolvedType, ActivityInfo aInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, Bundle options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) { int err = ActivityManager.START_SUCCESS; 。 。省略很多代码需要话去源码中看 。 err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask); if (err < 0) { // If someone asked to have the keyguard dismissed on the next // activity start, but we are not actually doing an activity // switch... just dismiss the keyguard now, because we // probably want to see whatever is behind it. notifyActivityDrawnForKeyguard(); } return err; } final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, Bundle options, TaskRecord inTask) { 。 。省略很多代码需要话去源码中看 。 targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options); if (!launchTaskBehind) { // Don't set focus on an activity that's going to the back. mService.setFocusedActivityLocked(r, "startedActivity"); } return ActivityManager.START_SUCCESS; } ActivityStack中 final void startActivityLocked(ActivityRecord r, boolean newTask, boolean doResume, boolean keepCurTransition, Bundle options) { 。 。省略很多代码需要话去源码中看 。 if (doResume) { mStackSupervisor.resumeTopActivitiesLocked(this, r, options); } } 再回到ActivityStackSupervisor中 boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, Bundle targetOptions) { if (targetStack == null) { targetStack = mFocusedStack; } // Do targetStack first. boolean result = false; if (isFrontStack(targetStack)) { result = targetStack.resumeTopActivityLocked(target, targetOptions); } for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks; for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = stacks.get(stackNdx); if (stack == targetStack) { // Already started above. continue; } if (isFrontStack(stack)) { stack.resumeTopActivityLocked(null); } } } return result; } 再次回到ActivityStack中 final boolean resumeTopActivityLocked(ActivityRecord prev) { return resumeTopActivityLocked(prev, null); } final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { if (mStackSupervisor.inResumeTopActivity) { // Don't even start recursing. return false; } boolean result = false; try { // Protect against recursion. mStackSupervisor.inResumeTopActivity = true; if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) { mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN; mService.updateSleepIfNeededLocked(); } result = resumeTopActivityInnerLocked(prev, options); } finally { mStackSupervisor.inResumeTopActivity = false; } return result; } private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) { { 。 。省略很多代码需要话去源码中看 。 mStackSupervisor.startSpecificActivityLocked(next, true, true); } if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); return true; } 再回到ActivityStackSupervisor中 void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { // Is this activity's application already running? ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true); r.task.stack.setLaunchTime(r); if (app != null && app.thread != null) { try { if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android".equals(r.info.packageName)) { // Don't add this if it is a platform component that is marked // to run in multiple processes, because this is actually // part of the framework so doesn't make sense to track as a // separate apk in the process. app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats); } realStartActivityLocked(r, app, andResume, checkConfig); return; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e); } // If a dead object exception was thrown -- fall through to // restart the application. } mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true); } final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { if (andResume) { r.startFreezingScreenLocked(app, 0); mWindowManager.setAppVisibility(r.appToken, true); // schedule launch ticks to collect information about slow apps. r.startLaunchTickingLocked(); } // Have the window manager re-evaluate the orientation of // the screen based on the new activity order. Note that // as a result of this, it can call back into the activity // manager with a new orientation. We don't care about that, // because the activity is not currently running so we are // just restarting it anyway. if (checkConfig) { Configuration config = mWindowManager.updateOrientationFromAppTokens( mService.mConfiguration, r.mayFreezeScreenLocked(app) ? r.appToken : null); mService.updateConfigurationLocked(config, r, false, false); } r.app = app; app.waitingToKill = null; r.launchCount++; r.lastLaunchTime = SystemClock.uptimeMillis(); if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r); int idx = app.activities.indexOf(r); if (idx < 0) { app.activities.add(r); } mService.updateLruProcessLocked(app, true, null); mService.updateOomAdjLocked(); final TaskRecord task = r.task; if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE || task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) { setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false); } final ActivityStack stack = task.stack; try { if (app.thread == null) { throw new RemoteException(); } List<ResultInfo> results = null; List<ReferrerIntent> newIntents = null; if (andResume) { results = r.results; newIntents = r.newIntents; } if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Launching: " + r + " icicle=" + r.icicle + " with results=" + results + " newIntents=" + newIntents + " andResume=" + andResume); if (andResume) { EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId, System.identityHashCode(r), task.taskId, r.shortComponentName); } if (r.isHomeActivity() && r.isNotResolverActivity()) { // Home process is the root process of the task. mService.mHomeProcess = task.mActivities.get(0).app; } mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName()); r.sleeping = false; r.forceNewConfig = false; mService.showAskCompatModeDialogLocked(r); r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo); ProfilerInfo profilerInfo = null; if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) { if (mService.mProfileProc == null || mService.mProfileProc == app) { mService.mProfileProc = app; final String profileFile = mService.mProfileFile; if (profileFile != null) { ParcelFileDescriptor profileFd = mService.mProfileFd; if (profileFd != null) { try { profileFd = profileFd.dup(); } catch (IOException e) { if (profileFd != null) { try { profileFd.close(); } catch (IOException o) { } profileFd = null; } } } profilerInfo = new ProfilerInfo(profileFile, profileFd, mService.mSamplingInterval, mService.mAutoStopProfiler); } } } if (andResume) { app.hasShownUi = true; app.pendingUiClean = true; } app.forceProcessStateUpTo(mService.mTopProcessState); app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo); if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) { // This may be a heavy-weight process! Note that the package // manager will ensure that only activity can run in the main // process of the .apk, which is the only thing that will be // considered heavy-weight. if (app.processName.equals(app.info.packageName)) { if (mService.mHeavyWeightProcess != null && mService.mHeavyWeightProcess != app) { Slog.w(TAG, "Starting new heavy weight process " + app + " when already running " + mService.mHeavyWeightProcess); } mService.mHeavyWeightProcess = app; Message msg = mService.mHandler.obtainMessage( ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG); msg.obj = r; mService.mHandler.sendMessage(msg); } } } catch (RemoteException e) { if (r.launchFailed) { // This is the second time we failed -- finish activity // and give up. Slog.e(TAG, "Second failure launching " + r.intent.getComponent().flattenToShortString() + ", giving up", e); mService.appDiedLocked(app); stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, "2nd-crash", false); return false; } // This is the first time we failed -- restart process and // retry. app.activities.remove(r); throw e; } r.launchFailed = false; if (stack.updateLRUListLocked(r)) { Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list"); } if (andResume) { // As part of the process of launching, ActivityThread also performs // a resume. stack.minimalResumeActivityLocked(r); } else { // This activity is not starting in the resumed state... which // should look like we asked it to pause+stop (but remain visible), // and it has done so and reported back the current icicle and // other state. if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to STOPPED: " + r + " (starting in stopped state)"); r.state = STOPPED; r.stopped = true; } // Launch the new version setup screen if needed. We do this -after- // launching the initial activity (that is, home), so that it can have // a chance to initialize itself while in the background, making the // switch back to it faster and look better. if (isFrontStack(stack)) { mService.startSetupActivityLocked(); } // Update any services we are bound to that might care about whether // their client may have activities. mService.mServices.updateServiceConnectionActivitiesLocked(r.app); return true; } 关键代码 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo); 通过看源码可以知道,app.thread是IApplicationThread的一个实现类,并且这个实现类是ActivityThread中的一个内部类 ApplicationThread 可以看到这里还有其他关于activity生命周期的方法 pause create destroy。。。。 @Override public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) { updateProcessState(procState, false); ActivityClientRecord r = new ActivityClientRecord(); r.token = token; r.ident = ident; r.intent = intent; r.referrer = referrer; r.voiceInteractor = voiceInteractor; r.activityInfo = info; r.compatInfo = compatInfo; r.state = state; r.persistentState = persistentState; r.pendingResults = pendingResults; r.pendingIntents = pendingNewIntents; r.startsNotResumed = notResumed; r.isForward = isForward; r.profilerInfo = profilerInfo; r.overrideConfig = overrideConfig; updatePendingConfiguration(curConfig); sendMessage(H.LAUNCH_ACTIVITY, r); } public void handleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); switch (msg.what) { case LAUNCH_ACTIVITY: { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart"); final ActivityClientRecord r = (ActivityClientRecord) msg.obj; r.packageInfo = getPackageInfoNoCheck( r.activityInfo.applicationInfo, r.compatInfo); handleLaunchActivity(r, null); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } break; private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) { // If we are getting ready to gc after going to the background, well // we are back active so skip it. unscheduleGcIdler(); mSomeActivitiesChanged = true; if (r.profilerInfo != null) { mProfiler.setProfiler(r.profilerInfo); mProfiler.startProfiling(); } // Make sure we are running with the most recent config. handleConfigurationChanged(null, null); if (localLOGV) Slog.v( TAG, "Handling launch of " + r); // Initialize before creating the activity WindowManagerGlobal.initialize(); Activity a = performLaunchActivity(r, customIntent); if (a != null) { r.createdConfig = new Configuration(mConfiguration); Bundle oldState = r.state; handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed); if (!r.activity.mFinished && r.startsNotResumed) { // The activity manager actually wants this one to start out // paused, because it needs to be visible but isn't in the // foreground. We accomplish this by going through the // normal startup (because activities expect to go through // onResume() the first time they run, before their window // is displayed), and then pausing it. However, in this case // we do -not- need to do the full pause cycle (of freezing // and such) because the activity manager assumes it can just // retain the current state it has. try { r.activity.mCalled = false; mInstrumentation.callActivityOnPause(r.activity); // We need to keep around the original state, in case // we need to be created again. But we only do this // for pre-Honeycomb apps, which always save their state // when pausing, so we can not have them save their state // when restarting from a paused state. For HC and later, // we want to (and can) let the state be saved as the normal // part of stopping the activity. if (r.isPreHoneycomb()) { r.state = oldState; } if (!r.activity.mCalled) { throw new SuperNotCalledException( "Activity " + r.intent.getComponent().toShortString() + " did not call through to super.onPause()"); } } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { if (!mInstrumentation.onException(r.activity, e)) { throw new RuntimeException( "Unable to pause activity " + r.intent.getComponent().toShortString() + ": " + e.toString(), e); } } r.paused = true; } } else { // If there was an error, for any reason, tell the activity // manager to stop us. try { ActivityManagerNative.getDefault() .finishActivity(r.token, Activity.RESULT_CANCELED, null, false); } catch (RemoteException ex) { // Ignore } } } private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")"); ActivityInfo aInfo = r.activityInfo; if (r.packageInfo == null) { r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo, Context.CONTEXT_INCLUDE_CODE); } ComponentName component = r.intent.getComponent(); if (component == null) { component = r.intent.resolveActivity( mInitialApplication.getPackageManager()); r.intent.setComponent(component); } if (r.activityInfo.targetActivity != null) { component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity); } Activity activity = null; try { java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); StrictMode.incrementExpectedActivityCount(activity.getClass()); r.intent.setExtrasClassLoader(cl); r.intent.prepareToEnterProcess(); if (r.state != null) { r.state.setClassLoader(cl); } } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to instantiate activity " + component + ": " + e.toString(), e); } } try { Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (localLOGV) Slog.v(TAG, "Performing launch of " + r); if (localLOGV) Slog.v( TAG, r + ": app=" + app + ", appName=" + app.getPackageName() + ", pkg=" + r.packageInfo.getPackageName() + ", comp=" + r.intent.getComponent().toShortString() + ", dir=" + r.packageInfo.getAppDir()); if (activity != null) { Context appContext = createBaseContextForActivity(r, activity); CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mCompatConfiguration); if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity " + r.activityInfo.name + " with config " + config); activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo, title, r.parent, r.embeddedID, r.lastNonConfigurationInstances, config, r.referrer, r.voiceInteractor); if (customIntent != null) { activity.mIntent = customIntent; } r.lastNonConfigurationInstances = null; activity.mStartedActivity = false; int theme = r.activityInfo.getThemeResource(); if (theme != 0) { activity.setTheme(theme); } activity.mCalled = false; if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } if (!activity.mCalled) { throw new SuperNotCalledException( "Activity " + r.intent.getComponent().toShortString() + " did not call through to super.onCreate()"); } r.activity = activity; r.stopped = true; if (!r.activity.mFinished) { activity.performStart(); r.stopped = false; } if (!r.activity.mFinished) { if (r.isPersistable()) { if (r.state != null || r.persistentState != null) { mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state, r.persistentState); } } else if (r.state != null) { mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state); } } if (!r.activity.mFinished) { activity.mCalled = false; if (r.isPersistable()) { mInstrumentation.callActivityOnPostCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnPostCreate(activity, r.state); } if (!activity.mCalled) { throw new SuperNotCalledException( "Activity " + r.intent.getComponent().toShortString() + " did not call through to super.onPostCreate()"); } } } r.paused = true; mActivities.put(r.token, r); } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to start activity " + component + ": " + e.toString(), e); } } return activity; } 关键代码 activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); 最终回到这里反射获取activity,于是我们终于知道了,activity是如何启动的,其实就是ClassLoader加载的 public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (Activity)cl.loadClass(className).newInstance(); } 具体ClassLoader是如何loadClass的,这就涉及到安卓类的加载机制,会在ClassLoader源码中进行分析

优秀的个人博客,低调大师

02.Jni开发流程_C/C++调用java

(创建于2017/11/18) c/c++调用Java包括几个分类,调用Java静态和非静态属性,静态和非静态方法四种 提示: 生成一个类中所有属性成员签名的方法如下: 1.进入这个类class文件所在的路径:如JniUtils这个类在d盘下 D:\application\java\eclipse-workspace\TestJni\bin\com\renzhenming\bsdiff> 2.执行命令D:\application\java\eclipse-workspace\TestJni\bin\com\renzhenming\bsdiff>javap -p -s JniUtils 3.会得到结果:descriptor所对应的就是签名 Compiled from "JniUtils.java" public class com.renzhenming.bsdiff.JniUtils { public static int key; descriptor: I static {}; descriptor: ()V public com.renzhenming.bsdiff.JniUtils(); descriptor: ()V public native void changeIntKey(); descriptor: ()V public native void accessMethod(); descriptor: ()V public native void accessStaticMethod(); descriptor: ()V public int getRandomInt(int); descriptor: (I)I public static java.lang.String getUUId(); descriptor: ()Ljava/lang/String; } 生成系统类签名的方法,以java.util.Date为例 直接进入命令行,输入javap -s -p 完整类名 C:\Users\renzhenming>javap -s -p java.util.Date Compiled from "Date.java" public class java.util.Date implements java.io.Serializable, java.lang.Cloneable, java.lang.Comparable<java.util.Date> { private static final sun.util.calendar.BaseCalendar gcal; descriptor: Lsun/util/calendar/BaseCalendar; private static sun.util.calendar.BaseCalendar jcal; descriptor: Lsun/util/calendar/BaseCalendar; private transient long fastTime; descriptor: J private transient sun.util.calendar.BaseCalendar$Date cdate; descriptor: Lsun/util/calendar/BaseCalendar$Date; private static int defaultCenturyStart; descriptor: I private static final long serialVersionUID; descriptor: J private static final java.lang.String[] wtb; descriptor: [Ljava/lang/String; private static final int[] ttb; descriptor: [I public java.util.Date(); descriptor: ()V public java.util.Date(long); descriptor: (J)V public java.util.Date(int, int, int); descriptor: (III)V public java.util.Date(int, int, int, int, int); descriptor: (IIIII)V public java.util.Date(int, int, int, int, int, int); descriptor: (IIIIII)V public java.util.Date(java.lang.String); descriptor: (Ljava/lang/String;)V public java.lang.Object clone(); descriptor: ()Ljava/lang/Object; public static long UTC(int, int, int, int, int, int); descriptor: (IIIIII)J public static long parse(java.lang.String); descriptor: (Ljava/lang/String;)J public int getYear(); descriptor: ()I public void setYear(int); descriptor: (I)V public int getMonth(); descriptor: ()I public void setMonth(int); descriptor: (I)V public int getDate(); descriptor: ()I public void setDate(int); descriptor: (I)V public int getDay(); descriptor: ()I public int getHours(); descriptor: ()I public void setHours(int); descriptor: (I)V public int getMinutes(); descriptor: ()I public void setMinutes(int); descriptor: (I)V public int getSeconds(); descriptor: ()I public void setSeconds(int); descriptor: (I)V public long getTime(); descriptor: ()J private final long getTimeImpl(); descriptor: ()J public void setTime(long); descriptor: (J)V public boolean before(java.util.Date); descriptor: (Ljava/util/Date;)Z public boolean after(java.util.Date); descriptor: (Ljava/util/Date;)Z public boolean equals(java.lang.Object); descriptor: (Ljava/lang/Object;)Z static final long getMillisOf(java.util.Date); descriptor: (Ljava/util/Date;)J public int compareTo(java.util.Date); descriptor: (Ljava/util/Date;)I public int hashCode(); descriptor: ()I public java.lang.String toString(); descriptor: ()Ljava/lang/String; private static final java.lang.StringBuilder convertToAbbr(java.lang.StringBuilder, java.lang.String); descriptor: (Ljava/lang/StringBuilder;Ljava/lang/String;)Ljava/lang/StringBuilder; public java.lang.String toLocaleString(); descriptor: ()Ljava/lang/String; public java.lang.String toGMTString(); descriptor: ()Ljava/lang/String; public int getTimezoneOffset(); descriptor: ()I private final sun.util.calendar.BaseCalendar$Date getCalendarDate(); descriptor: ()Lsun/util/calendar/BaseCalendar$Date; private final sun.util.calendar.BaseCalendar$Date normalize(); descriptor: ()Lsun/util/calendar/BaseCalendar$Date; private final sun.util.calendar.BaseCalendar$Date normalize(sun.util.calendar.BaseCalendar$Date); descriptor: (Lsun/util/calendar/BaseCalendar$Date;)Lsun/util/calendar/BaseCalendar$Date; private static final sun.util.calendar.BaseCalendar getCalendarSystem(int); descriptor: (I)Lsun/util/calendar/BaseCalendar; private static final sun.util.calendar.BaseCalendar getCalendarSystem(long); descriptor: (J)Lsun/util/calendar/BaseCalendar; private static final sun.util.calendar.BaseCalendar getCalendarSystem(sun.util.calendar.BaseCalendar$Date); descriptor: (Lsun/util/calendar/BaseCalendar$Date;)Lsun/util/calendar/BaseCalendar; private static final synchronized sun.util.calendar.BaseCalendar getJulianCalendar(); descriptor: ()Lsun/util/calendar/BaseCalendar; private void writeObject(java.io.ObjectOutputStream) throws java.io.IOException; descriptor: (Ljava/io/ObjectOutputStream;)V private void readObject(java.io.ObjectInputStream) throws java.io.IOException, java.lang.ClassNotFoundException; descriptor: (Ljava/io/ObjectInputStream;)V public static java.util.Date from(java.time.Instant); descriptor: (Ljava/time/Instant;)Ljava/util/Date; public java.time.Instant toInstant(); descriptor: ()Ljava/time/Instant; public int compareTo(java.lang.Object); descriptor: (Ljava/lang/Object;)I static {}; descriptor: ()V } C:\Users\renzhenming> 1.在Java的一个类中,如下,定义各种类型的属性和方法 import java.util.Random; import java.util.UUID; public class JniUtils { public String key = "renzhenming"; private Human human = new Man(); public static int count = 9; public native static String getStringFromC(); public native String getString2FromC(int i); //访问属性,返回修改之后的属性内容 public native String accessField(); public native void accessStaticField(); public native void accessMethod(); public native void accessStaticMethod(); public native void accessNonVirtualMethod(); public native String toChineseString(String value); public native void accessConstructor(); public native void setArray(int [] arr); public native int[] getArray(); public native void cached(); public native static void initIds(); public static void main(String[] args) { String text = getStringFromC(); System.out.println(text); JniUtils t = new JniUtils(); text = t.getString2FromC(6); System.out.println(text); System.out.println("key修改前:"+t.key); t.accessField(); System.out.println("key修改后:"+t.key); System.out.println("count修改前:"+count); t.accessStaticField(); System.out.println("count修改后:"+count); t.accessMethod(); t.accessStaticMethod(); System.out.println("访问构造方法"); new JniUtils().accessConstructor(); System.out.println("访问被子类重写后的父类方法"); new JniUtils().accessNonVirtualMethod(); System.out.println(new JniUtils().toChineseString("想乱码的日子里")); int arr [] = {12,3,43,55,44,1,566}; new JniUtils().setArray(arr); for(int i = 0 ; i < arr.length;i++ ) { System.out.println(arr[i]); } System.out.println("-------------------------------"); int [] jarr = new JniUtils().getArray(); for(int i = 0 ; i < jarr.length;i++ ) { System.out.println(jarr[i]); } System.out.println("-------------------------------"); new JniUtils().createGlobalRef(); System.out.println(new JniUtils().getGlobalRef()); new JniUtils().deleteGlobalRef(); //释放了再获取就会空指针 //System.out.println(new JniUtils().getGlobalRef()); try { new JniUtils().exception(); } catch (Exception e) { System.out.println("发生异常:"+e.getMessage()); } //不断调用cached方法 for (int i = 0; i < 100; i++) { t.cached(); } } //产生指定范围的随机数 public int genRandomInt(int max){ System.out.println("genRandomInt 执行了..."); return new Random().nextInt(max); } //产生UUID字符串 public static String getUUID(){ return UUID.randomUUID().toString(); } //加载动态库 static{ System.loadLibrary("JniTest");//这是生成的dll动态库的名字 initIds(); } } //类Human和类Man代码如下(测试jni调用父类方法而设置): public class Human { public void sayHi() { System.out.println("人打招呼"); } } public class Man extends Human{ public void sayHi() { System.out.println("男。。。。。人打招呼"); } } 2.创建native方法,使用javah生成头文件 /* DO NOT EDIT THIS FILE - it is machine generated */ #include "jni.h" /* Header for class com_dongnaoedu_jni_JniTest */ #ifndef _Included_com_renzhenming_bsdiff_JniUtils #define _Included_com_renzhenming_bsdiff_JniUtils #ifdef __cplusplus extern "C" { #endif /* * Class: _com_renzhenming_bsdiff_JniUtils * Method: getStringFromC * Signature: ()V */ JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_getStringFromC (JNIEnv *, jclass); JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_getString2FromC (JNIEnv *, jobject, jint); JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessField (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessStaticField (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessMethod (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessStaticMethod (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessConstructor (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessNonVirtualMethod (JNIEnv *, jobject); JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_toChineseString (JNIEnv *, jobject, jstring); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_setArray (JNIEnv *,jobject,jintArray); JNIEXPORT jintArray JNICALL Java_com_renzhenming_bsdiff_JniUtils_getArray (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_localRef (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_createGlobalRef (JNIEnv *,jobject); JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_getGlobalRef (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_deleteGlobalRef (JNIEnv *, jobject); JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_exception (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif 3.将头文件引入as中(jni.h和jni_md.h引入同上次笔记),编写c代码,如下 #define _CRT_SECURE_NO_WARNINGS #include "com_renzhenming_bsdiff_JniUtils.h" #include <string.h> //功能:获取到指定类中一字符串类型成员变量,修改返回得到新的字符串 JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_changeKey (JNIEnv *env, jobject jobj) { //我们编写的native方法是非静态方法,所以这里是jobject,而我们需要jclass来获取fieldid,所以这样转换 jclass clazz = (*env)->GetObjectClass(env, jobj); //参数分别为class对象,属性名,属性签名(签名得到的方法查看文档),获取到我们需要修改的属性的id值 jfieldID fieldId = (*env)->GetFieldID(env, clazz, "key", "Ljava/lang/String;"); //从这个对象jobj中获取这个id fieldid的jstring 对象 jstring jstr = (*env)->GetObjectField(env, jobj, fieldId); //将jni类型jstring 转换为c对象char ,从而我们可以调用c方法修改这个对象的值 char *c_str = (*env)->GetStringUTFChars(env, jstr, JNI_FALSE); //将这个对象的值和text这个字符串连接得到我们需要的新值 char text[30] = "handsome "; strcat(text, c_str); //再次将这个新值对应的c对象char转换为jni类型jstring, jstring new_jstr = (*env)->NewStringUTF(env, text); //将这个jstring类型的新对象设置给这个jobj这个对象中id值为fieldId的这个对象,至此对象值已经被我们修改 (*env)->SetObjectField(env, jobj, fieldId, new_jstr); //删除 (*env)->DeleteLocalRef(env,new_jstr); //返回这个新的字符串,这里没有用到 return new_jstr; } #define _CRT_SECURE_NO_WARNINGS #include "com_renzhenming_bsdiff_JniUtils.h" #include <string.h> //函数实现 JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_getStringFromC (JNIEnv *env, jclass jcls){ return (*env)->NewStringUTF(env,"C String"); } JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_getString2FromC (JNIEnv *env, jobject jobj, jint num){ return (*env)->NewStringUTF(env,"C String2"); } //每个native函数,都至少有两个参数(JNIEnv*,jclass或者jobject) //1)当native方法为静态方法时: //jclass 代表native方法所属类的class对象(JniTest.class) //2)当native方法为非静态方法时: //jobject 代表native方法所属的对象 //基本数据 //Java基本数据类型与JNI数据类型的映射关系 //Java类型->JNI类型->C类型 /* boolean jboolean byte jbyte; char jchar; short jshort; int jint; long jlong; float jfloat; double jdouble; void void */ //引用类型(对象) //String jstring //object jobject //数组,基本数据类型的数组 //byte[] jByteArray //对象数组 //object[](String[]) jobjectArray //C/C++访问Java的成员 //1.访问属性 //修改属性key JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessField (JNIEnv *env, jobject jobj){ //我们编写的native方法是非静态方法,所以这里是jobject,而我们需要jclass来获取fieldid,所以这样转换 jclass clazz = (*env)->GetObjectClass(env, jobj); //参数分别为class对象,属性名,属性签名(签名得到的方法查看文档),获取到我们需要修改的属性的id值 jfieldID fieldId = (*env)->GetFieldID(env, clazz, "key", "Ljava/lang/String;"); //从这个对象jobj中获取这个id fieldid的jstring 对象 jstring jstr = (*env)->GetObjectField(env, jobj, fieldId); //将jni类型jstring 转换为c对象char ,从而我们可以调用c方法修改这个对象的值 char *c_str = (*env)->GetStringUTFChars(env, jstr, JNI_FALSE); //将这个对象的值和text这个字符串连接得到我们需要的新值 char text[30] = "handsome "; strcat(text, c_str); //再次将这个新值对应的c对象char转换为jni类型jstring, jstring new_jstr = (*env)->NewStringUTF(env, text); //将这个jstring类型的新对象设置给这个jobj这个对象中id值为fieldId的这个对象,至此对象值已经被我们修改 (*env)->SetObjectField(env, jobj, fieldId, new_jstr); (*env)->DeleteLocalRef(env,new_jstr); //返回这个新的字符串,这里没有用到 return new_jstr; } //访问静态属性 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessStaticField (JNIEnv *env, jobject jobj){ //jclass jclass cls = (*env)->GetObjectClass(env, jobj); //jfieldID jfieldID fid = (*env)->GetStaticFieldID(env, cls, "count", "I"); //GetStatic<Type>Field jint count = (*env)->GetStaticIntField(env, cls, fid); count++; //修改 //SetStatic<Type>Field (*env)->SetStaticIntField(env,cls,fid,count); } //2.访问java方法 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessMethod (JNIEnv *env, jobject jobj){ //jclass jclass cls = (*env)->GetObjectClass(env, jobj); //jmethodID jmethodID mid = (*env)->GetMethodID(env, cls, "genRandomInt", "(I)I"); //调用 //Call<Type>Method jint random = (*env)->CallIntMethod(env, jobj, mid, 200); printf("random num:%ld",random); //..... } //静态方法 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessStaticMethod (JNIEnv *env, jobject jobj){ //jclass jclass cls = (*env)->GetObjectClass(env, jobj); //jmethodID jmethodID mid = (*env)->GetStaticMethodID(env, cls, "getUUID", "()Ljava/lang/String;"); //调用 //CallStatic<Type>Method jstring uuid = (*env)->CallStaticObjectMethod(env, cls, mid); //随机文件名称 uuid.txt //jstring -> char* //isCopy JNI_FALSE,代表java和c操作的是同一个字符串 char *uuid_str = (*env)->GetStringUTFChars(env, uuid, JNI_FALSE); //拼接 char filename[100]; sprintf(filename, "D://%s.txt",uuid_str); //w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。 FILE *fp = fopen(filename,"w"); fputs("i love jason", fp); fclose(fp); } //访问构造方法(Date 生成一个时间戳) JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessConstructor (JNIEnv *env, jobject jobj) { //根据包名得到类,类似反射 jclass cls = (*env)->FindClass(env, "java/util/Date"); //获取类中要获取的方法id(获取构造方法,方法名传"<init>") jmethodID methodid = (*env)->GetMethodID(env, cls, "<init>", "()V"); //实例化一个对象,类似反射 jobject date_obj = (*env)->NewObject(env, cls, methodid); //通过这个对象调用getTime方法,需要获取到这个方法的id jmethodID g_methodid = (*env)->GetMethodID(env, cls, "getTime", "()J"); //执行这个方法,返回值是long类型,所以CallLong jlong time = (*env)->CallLongMethod(env, date_obj, g_methodid); //占位符用的lld,是long long类型的,如果直接用ld占位符打印,打出的是负数 printf("\ntime:%lld\n", time); (*env)->DeleteLocalRef(env,date_obj); } //访问父类被子类重写的方法 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_accessNonVirtualMethod (JNIEnv *env, jobject jobj) { //在java中,父类指向子类对象,调用被子类重写的方法,执行的是子类的方法,在jni中 //我们可以调用到父类的方法 jclass cls = (*env)->GetObjectClass(env, jobj); //获取类中human属性(先获取到id) 对象的签名 jfieldID fid = (*env)->GetFieldID(env, cls, "human", "Lcom/renzhenming/bsdiff/Human;"); jobject human_obj = (*env)->GetObjectField(env, jobj, fid); //获取父类class jclass human_class = (*env)->FindClass(env, "com/renzhenming/bsdiff/Human"); //获取父类中需要调用的方法的methodid jmethodID s_mid = (*env)->GetMethodID(env,human_class,"sayHi","()V"); //执行指定方法 //子类方法 (*env)->CallObjectMethod(env, human_obj, s_mid); //父类方法(c++中要重写父类方法,用的是virtual关键字)(调用父类方法传入的class不能通过 //GetObjectClass从human_obj中获取,因为这样获取到的是子类的class) (*env)->CallNonvirtualObjectMethod(env, human_obj, human_class, s_mid); } //解决jni中文乱码的问题 JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_toChineseString_ (JNIEnv *env, jobject jobj, jstring jstr) { //输出 //char *c_str = (*env)->GetStringUTFChars(env, in, JNI_FALSE); //printf("%s\n",c_str); //c -> jstring char *c_str = "马蓉与宋江"; //char c_str[] = "马蓉与宋喆"; //jstring jstr = (*env)->NewStringUTF(env, c_str); //执行String(byte bytes[], String charsetName)构造方法需要的条件 //1.jmethodID //2.byte数组 //3.字符编码jstring jclass str_cls = (*env)->FindClass(env, "java/lang/String"); jmethodID constructor_mid = (*env)->GetMethodID(env, str_cls, "<init>", "([BLjava/lang/String;)V"); //jbyte -> char //jbyteArray -> char[] jbyteArray bytes = (*env)->NewByteArray(env, strlen(c_str)); //byte数组赋值 //0->strlen(c_str),从头到尾 //对等于,从c_str这个字符数组,复制到bytes这个字符数组 (*env)->SetByteArrayRegion(env, bytes, 0, strlen(c_str), c_str); //字符编码jstring jstring charsetName = (*env)->NewStringUTF(env, "GB2312"); //调用构造函数,返回编码之后的jstring return (*env)->NewObject(env, str_cls, constructor_mid, bytes, charsetName); } //-----------------------操作数组涉及到数组的同步问题(ReleaseIntArrayElements)-----------------------------// //操作传入的数组 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_setArray (JNIEnv *env, jobject jobj, jintArray array) { //jintArray ->jint指针->c int数组 jint *elems = (*env)->GetIntArrayElements(env, array, JNI_FALSE); //数组的长度 int len = (*env)->GetArrayLength(env, array); //排序(传入的compare类似Java中的比较器) qsort(elems, len, sizeof(jint), compare); //将排序结果同步到Java中的数组 //最后一个参数 mode //0 表示Java数组进行更新,并且释放c/c++数组 //JNI_ABORT 表示Java数组不更新,释放c/c++数组 //JNI_COMMIT 表示Java数组进行更新,但不释放c/c++数组 (*env)->ReleaseIntArrayElements(env, array, elems, 0); } //返回一个数组 JNIEXPORT jintArray JNICALL Java_com_renzhenming_bsdiff_JniUtils_getArray (JNIEnv *env, jobject jobj) { //创建一个指定大小的数组 jintArray jint_arr = (*env)->NewIntArray(env, 10); //获取到数组指针 jint *elems = (*env)->GetIntArrayElements(env, jint_arr, NULL); int i = 0; for ( ; i< 10; i++) { elems[i] = i; } //同步 (*env)->ReleaseIntArrayElements(env, jint_arr, elems, 0); return jint_arr; } //局部引用 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_localRef (JNIEnv *env, jobject jobj) { int i = 0; for (; i < 5; i++) { //创建对象,以Date为例 jclass cls = (*env)->FindClass(env, "java/util/Date"); jmethodID constructor_id = (*env)->GetMethodID(env, cls, "init", "()V"); jobject obj = (*env)->NewObject(env, cls, constructor_id); //.... //不在使用这个对象了需要回收 (*env)->DeleteLocalRef(env, obj); //.... } } //创建全局引用(共享,可以跨多个线程) jstring global_str; JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_createGlobalRef (JNIEnv *env, jobject jobj) { jstring jstr = (*env)->NewStringUTF(env,"jni is a bitch"); global_str = (*env)->NewGlobalRef(env, jstr); } //获取全局引用 JNIEXPORT jstring JNICALL Java_com_renzhenming_bsdiff_JniUtils_getGlobalRef (JNIEnv *env, jobject jobj) { return global_str; } //删除全局引用 JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_deleteGlobalRef (JNIEnv *env, jobject jobj) { (*env)->DeleteGlobalRef(env, global_str); } //Java捕获c异常(如果不做抛异常处理,直接再Java层try是抓不到异常信息的) JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_exception (JNIEnv *env, jobject jobj) { jclass cls = (*env)->GetObjectClass(env, jobj); jfieldID fid = (*env)->GetFieldID(env, cls, "value2", "Ljava/lang/String;"); //检测是否发生Java异常 jthrowable exception = (*env)->ExceptionOccurred(env); if (exception != NULL) { //让Java代码可以继续运行 //清空异常信息 (*env)->ExceptionClear(env); //补救措施 fid = (*env)->GetFieldID(env, cls, "value", "Ljava/lang/String;"); } //获取属性值 jstring jstr = (*env)->GetObjectField(env, jobj, fid); char *str = (*env)->GetStringUTFChars(env, jstr, NULL); //对比属性是否合法 if (stricmp(str, "renzhenming") != 0) { //抛出异常,给Java处理 jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); (*env)->ThrowNew(env, newExcCls, "key's value is invalid!"); } } //静态缓存 //static jfieldID key_id JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_cached(JNIEnv *env, jobject jobj){ jclass cls = (*env)->GetObjectClass(env, jobj); //»ñÈ¡jfieldIDÖ»»ñȡһ´Î //¾Ö²¿¾²Ì¬±äÁ¿ static jfieldID key_id = NULL; if (key_id == NULL){ key_id = (*env)->GetFieldID(env, cls, "key", "Ljava/lang/String;"); printf("--------GetFieldID-------\n"); } } //加载动态库的时候就初始化全局变量,再loadLibrary后调用 jfieldID key_fid; jmethodID random_mid; JNIEXPORT void JNICALL Java_com_renzhenming_bsdiff_JniUtils_initIds(JNIEnv *env, jclass jcls){ key_fid = (*env)->GetFieldID(env, jcls, "key", "Ljava/lang/String;"); random_mid = (*env)->GetMethodID(env, jcls, "genRandomInt", "(I)I"); } 4.生成dll动态库,放到eclipse中调用 public static void main(String[] args) { String text = getStringFromC(); System.out.println(text); JniTest t = new JniTest(); text = t.getString2FromC(6); System.out.println(text); System.out.println("key修改前:"+t.key); t.accessField(); System.out.println("key修改后:"+t.key); System.out.println("count修改前:"+count); t.accessStaticField(); System.out.println("count修改后:"+count); t.accessMethod(); t.accessStaticMethod(); System.out.println("访问构造方法"); new JniUtils().accessConstructor(); System.out.println("访问被子类重写后的父类方法"); new JniUtils().accessNonVirtualMethod(); System.out.println(new JniUtils().toChineseString("想乱码的日子里")); int arr [] = {12,3,43,55,44,1,566}; new JniUtils().setArray(arr); for(int i = 0 ; i < arr.length;i++ ) { System.out.println(arr[i]); } System.out.println("-------------------------------"); int [] jarr = new JniUtils().getArray(); for(int i = 0 ; i < jarr.length;i++ ) { System.out.println(jarr[i]); } System.out.println("-------------------------------"); new JniUtils().createGlobalRef(); System.out.println(new JniUtils().getGlobalRef()); new JniUtils().deleteGlobalRef(); //释放了再获取就会空指针 //System.out.println(new JniUtils().getGlobalRef()); try { new JniUtils().exception(); } catch (Exception e) { System.out.println("发生异常:"+e.getMessage()); } }

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册